String to decimal conversion: dot separation instead of comma

LoveMyWife picture LoveMyWife · Nov 10, 2013 · Viewed 124.4k times · Source

I have a string read from a textbox. It contains a comma for decimal separation.

I have NumberFormatInfo.CurrencyDecimalSeparator set to , (comma) but when I convert the string to decimal Convert.ToDecimal(mystring); I obtain a dot separate value for decimal.

Example:

decimal a=Convert.ToDecimal("1,2345"); ----> decimal is 1.2345

I have tried also:

double a=Convert.ToDouble("1,2345"); 

but dot for decimal again

Answer

Agat picture Agat · Nov 10, 2013

All this is about cultures. If you have any other culture than "US English" (and also as good manners of development), you should use something like this:

var d = Convert.ToDecimal("1.2345", new CultureInfo("en-US"));
// (or 1,2345 with your local culture, for instance)

(obviously, you should replace the "en-US" with the culture of your number local culture)

the same way, if you want to do ToString()

d.ToString(new CultureInfo("en-US"));