c# decimal toString() conversion with comma(,)

后端 未结 5 1153
轮回少年
轮回少年 2021-02-08 11:11

c# decimal.toString() conversion problem

Example: I have a value in decimal(.1) when I convert decimal to string using toString() it return

相关标签:
5条回答
  • 2021-02-08 11:11

    I believe this is to do with the culture/region which your operating system is set to. You can fix/change the way the string is parsed by adding in a format overload in the .ToString() method.

    For example

    decimalValue.ToString(CultureInfo.InvariantCulture);
    
    0 讨论(0)
  • 2021-02-08 11:17

    For this to be happening, the thread's current culture must be one that uses a separator of comma instead of dot.

    You can change this on a per ToString basis using the overload for ToString that takes a culture:

    var withDot = myVal.ToString(CultureInfo.InvariantCulture);
    

    Alternatively, you can change this for the whole thread by setting the thread's culture before performing any calls to ToString():

    var ci = CultureInfo.InvariantCulture;
    Thread.CurrentThread.CurrentCulture = ci;
    Thread.CurrentThread.CurrentUICulture = ci;
    
    var first = myVal.ToString();
    var second = anotherVal.ToString();
    
    0 讨论(0)
  • 2021-02-08 11:23

    For comma (,)

    try this:

    decimalValue.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("tr-tr"))
    
    0 讨论(0)
  • 2021-02-08 11:26

    you have to define the format, it will depend in your local setting or define the format, using something like this

    decimal.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("en-us"));
    

    cheers

    0 讨论(0)
  • 2021-02-08 11:34

    Then your current culture's NumberDecimalSeparator is , instead of ..

    If that's not desired you can force the dot with CultureInfo.InvariantCulture:

    decimal num = 0.1m;
    string numWithDotAsSeparator = num.ToString(CultureInfo.InvariantCulture);
    

    or NumberFormatInfo.InvariantInfo

    string numWithDotAsSeparator = num.ToString(NumberFormatInfo.InvariantInfo)
    
    0 讨论(0)
提交回复
热议问题