1

I have a web app, where users can change their locale, however when a user changes locale to french Canadian "fr-CA" a double conversion is throwing invalid format string error. What happens is that I am getting some data from database where double values come out as string e.g "232.33". Problem is this string can not be converted to a double using Parse or any of its variants...I wonder some one can shed some light on how to parse this double so that fr-CA locale allow me to get double d=232.33

Thanks

4

1 回答 1

2

The Parse and ToString methods are culture specific, as you've probably noticed.

If you're always expecting these to be in the invariant culture (format 232.33 instead of 232,33)

You can use the overload of Parse that lets you specify the number format

decimal myDecimal = decimal.Parse("232.33", CultureInfo.InvariantCulture);

The same goes for converting a decimal to string

decimal myDecimal = 232.33m;

string myString = myDecimal.ToString(CultureInfo.InvariantCulture); // "232.33" regardless of current threads culture

See resources:

http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.invariantculture.aspx

Slightly off topic, but you should be storing decimals in the database as the proper numeric type instead of strings. This way you can use aggregates and math in your queries if need be, plus you get better storage optimizations, and you won't have to parse strings.

于 2013-08-31T04:26:55.027 回答