If you’ll format a float to a locale string (i.e. Euro), you’ll get very different results in every browser. So you may are interested how to fix that without coding an own function for formatting currencies? Here you are! This Post is how to do that.

The issue about toLocaleString()

If you try to format a float to a locale string (i.e. Euro), you’ll get very different results in every browser. This is because toLocaleString() does not format your currencies, the browser does. toLocaleString() is only calling browsers to do so. toLocaleString can be implemented however the developers wish.

Example

This examples tries to convert a float to a pretty german EUR currency value with use of toLocaleString(). Best how it should output is 2.282,00 EUR

var sum=2282.00;
var formated_sum = Number(sum).toLocaleString("de-DE", {style: "currency", currency: "EUR"});

This is, how the output looks like in different browser

This is, how it looks like if you are coverting with toLocaleString()

Browser Output
Firefox: 2.282,00 €
Chrome: 2.282 €
IE 8+: 2.282,00 €
Safari: 2282 €

Safari results are very much wrong, chrome results are not so much bad. So there is an interest how to fix that without coding an own function for formatting currencies.

How to fix that issue with toLocaleString

Best way i have found to do so is accounting.js

Example for accounting.js

var sum = 2282.00;
$.getScript('/js/accounting.min.js', function(sum){
  var endpreis_formated = accounting.formatMoney(sum, "", 2, ".", ",") + ' EUR';
});
  • jQuery used to include accounting.min.js

This is how the output’ll looks like

Browser Darstellung
Firefox: 2.282,00 EUR
Chrome: 2.282,00 EUR
IE 8+: 2.282,00 EUR
Safari: 2.282,00 EUR

That is a pretty much better result!

This transformation of a float does convert it only in one specified currency. If you want to convert it to users unknown locale, you have to use: accounting.formatMoney(sum); without a specified parameters. Thanks to George Ruethschilling for that hint.

Diesen Beitrag gibt es auch auf deutsch