convert this string into decimal

前端 未结 4 1573
抹茶落季
抹茶落季 2020-12-04 03:59

Sounds easy but when I tried to achieve i\'m stock about how is the formatter to make this conversion this are some examples of strings that i need to convert to decimal

相关标签:
4条回答
  • 2020-12-04 04:16

    I think Decimal.TryParse should work. More info here.

    0 讨论(0)
  • 2020-12-04 04:33

    Why not just use Decimal.Parse

    decimal x = Decimal.Parse("00.24");
    Console.WriteLine(x);  // Prints: 00.24
    
    0 讨论(0)
  • 2020-12-04 04:33

    The result you're getting is because the dot . is tretaed as a group (thousand) separator. the parser simply discards it, and doesn't check if the group sizes are right. So '20.100.200' or '1.2.3.4' would also get parsed as 20100200 and 1234.

    This happens on many european cultures, like 'es'

    You have to use any culture that doesn't consider a . as a group separator, but as a decimal separator. CultureInfo.InvariantCulture is one of the possible cultures (it has basically the same configuration of en-US).

    0 讨论(0)
  • 2020-12-04 04:35

    I suspect your system culture is not English and has different number formatting rules. Try passing the invariant culture as the format provider:

    decimal d = Convert.ToDecimal("00.24", CultureInfo.InvariantCulture);
    

    You could also use Decimal.Parse:

    decimal d = Decimal.Parse("00.24", CultureInfo.InvariantCulture);
    
    0 讨论(0)
提交回复
热议问题