Choose a standard number format

Jan 18, 2007

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.

* $4.95/month BlogEngine.net Hosting – Click Here!

Comments (2) -

 Mike
Mike
1/19/2007 12:04:27 AM #

Im not sure how you guys do it over there, but having lived in the Unites States for a long time, I can say with some certainty that we format "two thousand decimal one two five" as 2000.125
Tong

Mads Kristensen
Mads Kristensen
1/19/2007 5:26:02 AM #

Thanks Mike. It's fixed now. Makes you think when spell-checkers become smart enough to catch logical mistakes as well Smile

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.