Javascript Number and Currency localization
Solution 1
Most modern browsers have built in support internationalisation in the form of the global Intl object and extensions to Number, String & Date.
var money = 123456.12;
// display with correct formatting
money.toLocaleString('de-DE'); // "123.456,12"
// for currency, bad as we're leaving the precision to the gods of floating point numbers
money.toLocaleString('en-GB', { style: 'currency', currency: 'GBP' }); // "£123,456.12"
// for currency, good as we're using strings...
new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format('12312.12')
If you're not familiar with why floating point numbers are bad for currency info check this out on floating point numbers
Solution 2
The best answer for you probably depends on what javascript libary, if any, you are currently using. But YUI has support for number/currency formatting with internationalization, and it is a solid and well-designed library.
Example:
alert(Y.DataType.Number.format(123123123.176,{
prefix: "€",
thousandsSeparator: ".",
decimalSeparator: ",",
decimalPlaces: 2,
suffix: " (EUR)"
}));
Solution 3
Microsoft has created a useful plugin for jquery:
http://weblogs.asp.net/scottgu/archive/2010/06/10/jquery-globalization-plugin-from-microsoft.aspx
Solution 4
This post is quite old, but I post a response in case it's interesting someone.
I found the numeral.js library pretty useful to do this.
You can define your custom formats and add localized files in the same way that 'moment.js'.
You should probably check to see if it fits your needs.
Related videos on Youtube
Dan
Updated on May 28, 2022Comments
-
Dan almost 2 years
I've run into numbers and currency localization in JavaScript
What I need is a convenient library for that.
I am responsible for setting the decimal separators, currency, etc.
Please post the best links you think
-
bcoughlan over 11 yearsThe repository is dead, but I believe this is its replacement: github.com/jquery/globalize
-
Giorgio Tempesta almost 5 yearsThis looks like the best approach. Does anyone know of good polyfills for this?
-
Giorgio Tempesta almost 5 yearsOk after some research, it appears that the best resource as of may 2019 is the Intl package: github.com/andyearnshaw/Intl.js