[c#] String to decimal conversion: dot separation instead of comma

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

This question is related to c# decimal

The answer is


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"));

Instead of replace we can force culture like

var x = decimal.Parse("18,285", new NumberFormatInfo() { NumberDecimalSeparator = "," });

it will give output 18.285


I ended up using this solution.

decimal weeklyWage;
decimal.TryParse(items[2],NumberStyles.Any, new NumberFormatInfo() { NumberDecimalSeparator = "."}, out weeklyWage);

You are viewing your decimal or double values in Visual Studio. That doesn't respect the culture settings you have on your code.

Change the Region and Language settings on your Control Panel if you want to see decimal and double values having the comma as the decimal separator.


    usCulture = new CultureInfo("vi-VN");
Thread.CurrentThread.CurrentCulture = usCulture;
Thread.CurrentThread.CurrentUICulture = usCulture;
usCulture = Thread.CurrentThread.CurrentCulture;
dbNumberFormat = usCulture.NumberFormat;
number = decimal.Parse("1.332,23", dbNumberFormat); //123.456.789,00

usCulture = new CultureInfo("en-GB");
Thread.CurrentThread.CurrentCulture = usCulture;
Thread.CurrentThread.CurrentUICulture = usCulture;
usCulture = Thread.CurrentThread.CurrentCulture;
dbNumberFormat = usCulture.NumberFormat;
number = decimal.Parse("1,332.23", dbNumberFormat); //123.456.789,00

/*Decision*/
var usCulture = Thread.CurrentThread.CurrentCulture;
var dbNumberFormat = usCulture.NumberFormat;
decimal number;
decimal.TryParse("1,332.23", dbNumberFormat, out number); //123.456.789,00

I had faced the similar issue while using Convert.ToSingle(my_value) If the OS language settings is English 2.5 (example) will be taken as 2.5 If the OS language is German, 2.5 will be treated as 2,5 which is 25 I used the invariantculture IFormat provided and it works. It always treats '.' as '.' instead of ',' irrespective of the system language.

float var = Convert.ToSingle(my_value, System.Globalization.CultureInfo.InvariantCulture);