Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert "12,4" to decimal en-Us culture

Tags:

c#

cultureinfo

I have a decimal value ("133,3") stored in string column in the database, in norway culture.

after that user changed the regional setting to english-Us. when I convert "133,3" to decimal using CultureInfo.InvariantCulture, getting invalid value or error.

is there any best way to handle this scenario in C# application?

regards, Anand

like image 470
Anand Kumar Avatar asked Dec 01 '11 13:12

Anand Kumar


2 Answers

If you know the culture that was in use when persisting the value, you can use it when parsing it, i.e.:

Convert.ToDecimal("133,3", System.Globalization.CultureInfo.GetCultureInfo("no"));

Of course, you are probably better off changing how the data is stored in the database, to use a floating point number of some form.

like image 93
Rowland Shaw Avatar answered Oct 23 '22 07:10

Rowland Shaw


Regardless of the system culture, if you specify CultureInfo.InvariantCulture you won't be able to parse "133,3" as a decimal to 133.3. The same is true for US English.

You could just specify a Norwegian culture when parsing the value (using the overload of decimal.TryParse which takes an IFormatProvider), or (preferrably) change the field in the database to reflect the real data type (a decimal number) instead.

like image 35
Jon Skeet Avatar answered Oct 23 '22 06:10

Jon Skeet