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
The toFixed() method in JavaScript is used to format a number using fixed-point notation. It can be used to format a number with a specific number of digits to the right of the decimal. The toFixed() method is used with a number as shown in the above syntax using the '. ' operator.
In JavaScript, the easiest and most popular way to format numbers as currency strings is via the Intl. NumberFormat() method. This approach lets you format numbers using custom locale parameters - and in this article, we'll focus on currencies.
Intl.NumberFormat.prototype.format() Getter function that formats a number according to the locale and formatting options of this Intl.NumberFormat object. Intl.NumberFormat.prototype.formatToParts() Returns an Array of objects representing the number string in parts that can be used for custom locale-aware formatting.
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
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)"
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With