Choose a standard number format
Today, I ran into an issue regarding the way numbers are parsed in different cultures, which resulted in very wrong numbers. The problem begins when your web application is set to automatically resolve the culture through the browser. It is by default. All these different cultures have different ways to look at numbers and decimals and that’s all built directly into the .NET Framework.
The number one thousand decimal one two five is written differently in the various cultures. Here are some examples
1000,125 (European)
1000.125 (American)
Imagine that you have to parse XML files wherein the number format is European and you do it from an ASP.NET application with the culture set to en-US. The result of the parsing would be 1000125 – the whole number without decimals. But if the current culture was da-DK the result would be the expected one with three decimals.
So, to make sure your localized ASP.NET application parses the same XML files the correct way every time, you have to create an IFormatProvider to use when you parse the numbers. If the number format in the XML file (or any other place) is American, then you can use the following static property as IFormatProvider:
string number = "1000.125";
double dbl = double.Parse(number, NumberFormat);
private static NumberFormatInfo _NumberFormat;
/// <summary>
/// Gets a non localized NumberFormatInfo
/// </summary>
public static NumberFormatInfo NumberFormat
{
get
{
if (_NumberFormat == null)
{
_NumberFormat = new NumberFormatInfo();
_NumberFormat.NumberDecimalSeparator = ".";
}
return _NumberFormat;
}
}
The property only handles number formats and not currency or percentage formats, but they are easily applied the same with the decimal separator is.