Internationalization(number Formatting "num.tolocalestring()") Not Working For Chrome
Solution 1:
The toLocaleString()
method is by definition implementation-dependent: it uses the implementation locale, such as browser locale. So if I were looking at your page that uses the method, I would see numbers formatted according to Finnish or English locale, depending on which browser I’m using.
What you want is localization by the locale of the page, and for this you need something else. In simple cases you might code it yourself, but number formatting is in general complicated, making it reasonable to use a library, such as Globalize. Check out the compact source of a simple demo. In Globalize, you use standard language codes when specifying the locale.
Solution 2:
Internationalization is always challenging and unfortunately there doesn't seem to be a consistent/pervasive solution to it. Your best bet is to use a 3rd party library to take care of things for you. We rely heavily on googles closure library, which has some pretty powerful i18n (internationalization) tools. Take a look at http://www.daveoncode.com/2009/11/26/goog-i18n-numberformat-formatting-number-locale-string/ for an example of how to use it. In the end, it becomes as easy as:
//define italian number format symbols
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_it_IT;
//createnewdecimal formatter (PERCENT, CURRENCY, SCIENTIFIC are options)
formatter =new goog.i18n.NumberFormat(goog.i18n.NumberFormat.Format.DECIMAL);
//view formatted and localized string
alert(formatter.format(15650.579));
If you are new to closure, don't worry. It's not hard to get set up and has a multitude of excellent helper classes that you may find useful. http://code.google.com/closure/library/docs/gettingstarted.html
Solution 3:
The JavaScript internationalization support is quite poor (as you have discovered). You might take a look at https://github.com/jquery/globalize It handles number formatting, and also dates, times, currencies.
Solution 4:
A bit of voodoo can implement your own number formatting. You could build this into String.prototype, but I didnt want that, since its localized.
function reverse(str) {
return str.split('').reverse().join('');
}
function num2str(num) {
var str = num+"";
// european
// returnreverse(reverse(str.replace('.',',')).replace(/\d{3}/g,'$&.').replace(/\.$/,''));
// american
returnreverse(reverse(str).replace(/\d{3}/g,'$&,').replace(/\,$/,''));
}
and then its
> console.log(25000.45)> 25,000.45
Post a Comment for "Internationalization(number Formatting "num.tolocalestring()") Not Working For Chrome"