Localized Currencies and Decimals using MicrosoftAjax.js
09 Jul 2010

asp.net currency decimals javascript localization mvc


Although .NET is able to deal with localized currency and decimal values quite easily, client side JavaScript is not. The common JavaScript method for parsing a currency or decimal string into a number value is parseFloat(string). Unfortunately, this method is unable to parse currency or decimal strings formatted for certain cultures. For example, when using the "fr-FR" UI culture the value 2.75 is written as "2,75". Passing this string into the parseFloat(string) method will result in an incorrect result. Also, when formatting a number value to a string similar problems occur.

The MicrosoftAjax library contains various helper functions designed to deal with localized currency and decimal values within your JavaScript coding. The library comes included in the ASP.NET MVC project template courtesy of Visual Studio 2010. Simply create a new ASP.NET MVC project and the MicrosoftAjax.js file will be included in the project’s "Scripts" directory.

Visual Studio Solution Explorer

Visual Studio Solution Explorer

Simply add a reference to the script file within the <head> tag of your html content.

In order to make use of the MicrosoftAjax library it must first be configured by setting the desired UI culture, otherwise it defaults to "en-US". It is most likely that you will want the UI culture set to the user's browser culture. To configure your application to read the current culture from the user's selected browser culture add a <Globalization /> tag to the web.config.

This will populate the .NET System.Threading.Thread. CurrentThread.CurrentUICulture property, which must then be passed to the MicrosoftAjax library. This is achieved by setting the JavaScript variable Sys.CultureInfo.CurrentCulture with a serialized ClientCultureInfo object. The ClientCultureInfo class definition is shown below.

Instantiate a ClientCultureInfo object with the current UI culture and then set the JavaScript variable Sys.CultureInfo.CurrentCulture with the serialized object.

Once the MicrosoftAjax library has been included and configured correctly there are two main methods that are useful when dealing with localized currencies and decimals. The first method is Number.parseLocal(string). This method parses a decimal or currency string into a number value, taking into consideration the selected culture's defined number formatting properties.

So, for example, if the current culture was set to "fr-FR" the above code would output "2.75". Thus converting the localized string into the correct number value.

The second method is Number.localFormat(format). This method formats a decimal or currency value based on the current culture into a string.

So, for example, if the current culture was set to "fr-FR" the above code would output "2,75". Thus making use of the selected culture's defined number formatting properties.