How to convert "12.4" to decimal en-Us culture

I have a decimal value ("133.3") stored in a row column in a database in Norway.

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

Is there a better way to handle this scenario in a C # application?

Regards, Anand

+4
source share
6 answers

Regardless of the system culture, if you specify CultureInfo.InvariantCulture , you cannot parse "133.3" as decimal to 133.3. The same is true for American English.

You can specify Norwegian culture when analyzing the value (using the decimal.TryParse overload that accepts IFormatProvider ), or (preferably) change the field in the database to display the actual data type (decimal) instead.

+13
source

You reference Convert.ToDecimal () , it says how

 using System; using System.Globalization; public class Example { public static void Main() { string[] values = { "123456789", "12345.6789", "12 345,6789", "123,456.789", "123 456,789", "123,456,789.0123", "123 456 789,0123" }; CultureInfo[] cultures = { new CultureInfo("en-US"), new CultureInfo("fr-FR") }; foreach (CultureInfo culture in cultures) { Console.WriteLine("String -> Decimal Conversion Using the {0} Culture", culture.Name); foreach (string value in values) { Console.Write("{0,20} -> ", value); try { Console.WriteLine(Convert.ToDecimal(value, culture)); } catch (FormatException) { Console.WriteLine("FormatException"); } } Console.WriteLine(); } } } 
+8
source

If you know the culture that was used to store the value, you can use it to parse it, that is:

 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, using some form of floating point.

+3
source
 Convert.ToDouble(textBox2.Text, new CultureInfo("uk-UA")).ToString(new CultureInfo("en-US")); 
+3
source

This solves your problem: .ToString (New CultureInfo ("en-US"))

+1
source

used below code to fix my problem. I just encoded the previous decimal point. may not be shared. but solved my problem.

 public static decimal? ToDecimal1(this string source) { CultureInfo usCulture = new CultureInfo("en-US"); if (string.IsNullOrEmpty(source.Trim1())) return null; else return Convert.ToDecimal(source.Replace(",", ".").Trim(), usCulture); } 
0
source

Source: https://habr.com/ru/post/1384110/


All Articles