Thursday, March 4, 2021

C# - String convert/Parse to double/Currency where conatins "," as decimal separator

in C# when we try to convert a string to double say 123,45, Convert/Parse operator consider "," as a string format character and it will ignore "," from the string and return 12345.

double dbl = Double.TryParse("123,45")

output : 12345

Above piece of code works in German/France locale. Because decimal separator in GE/FR is comma(",") instead of "dot" (".")


To resolve this issue, it will be good to parse the string with culture like below

double dbConvertNumber= 0;

Double.TryParse("123,45", System.Globalization.NumberStyles.Any,
System.Globalization.NumberFormatInfo.CurrentInfo, dbConvertNumber)

Console.WriteLine (dbConvertNumber)

output : 0 in "us\UK" locale
             123,45 in "GE\FR" locale