Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Number and Currency localization [closed]

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

like image 864
Dan Avatar asked Apr 11 '11 16:04

Dan


People also ask

How do you format numbers in JavaScript?

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.

How do you use currency in JavaScript?

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.

What is Intl NumberFormat?

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.


2 Answers

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

like image 118
Ian Chadwick Avatar answered Sep 24 '22 13:09

Ian Chadwick


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)"
}));
like image 24
Gabe Moothart Avatar answered Sep 25 '22 13:09

Gabe Moothart