Converting double to string with N decimals, dot as decimal separator, and no thousand separator

后端 未结 7 2009
礼貌的吻别
礼貌的吻别 2020-12-28 11:43

I need to convert a decimal to a string with N decimals (two or four) and NO thousand separator:

\'XXXXXXX (dot) DDDDD\'

The problem with CultureInfo.I

相关标签:
7条回答
  • 2020-12-28 12:05

    It's really easy to specify your own decimal separator. Just took me about 2 hours to figure it out :D. You see that you were using the current ou other culture that you specify right? Well, the only thing the parser needs is an IFormatProvider. If you give it the CultureInfo.CurrentCulture.NumberFormat as a formatter, it will format the double according to your current culture's NumberDecimalSeparator. What I did was just to create a new instance of the NumberFormatInfo class and set it's NumberDecimalSeparator property to whichever separator string I wanted. Complete code below:

    double value = 2.3d;
    NumberFormatInfo nfi = new NumberFormatInfo();
    nfi.NumberDecimalSeparator = "-";
    string x = value.ToString(nfi);
    

    The result? "2-3"

    0 讨论(0)
  • 2020-12-28 12:05
    double value = 3.14159D;
    string v = value.ToString().Replace(",", ".");
    Console.WriteLine(v);
    

    Output: 3.14159

    0 讨论(0)
  • 2020-12-28 12:08

    You can use

    value.ToString(CultureInfo.InvariantCulture)
    

    to get exact double value without putting precision.

    0 讨论(0)
  • 2020-12-28 12:18

    For a decimal, use the ToString method, and specify the Invariant culture to get a period as decimal separator:

    value.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)
    

    The long type is an integer, so there is no fraction part. You can just format it into a string and add some zeros afterwards:

    value.ToString() + ".00"
    
    0 讨论(0)
  • 2020-12-28 12:19

    I prefer to use ToString() and IFormatProvider.

    double value = 100000.3
    Console.WriteLine(value.ToString("0,0.00", new CultureInfo("en-US", false)));
    

    Output: 10,000.30

    0 讨论(0)
  • 2020-12-28 12:25

    I think you could have used:
    value.ToString("F"+NumberOfDecimals)

    value = 10,502
    value.ToString("F2") //10,50
    value = 10,5 
    value.ToString("F2") //10,50
    

    Here is a detailed description of Numeric Format Strings

    0 讨论(0)
提交回复
热议问题