Number Formatting In JavaScript

Number Formatting In JavaScript

JavaScript

Numbers are one of the biggest problems I have encountered when number formatting of server and the client is different. It gets a little messy with all these dots and commas.

As you know, in US or UK numeric system, "thousand" numbers are separated with "," and decimal numbers are separated with "." whereas in EU Countries , it is the opposite. "Thousand" numbers are separated by "." while decimal parts are separated by ","

People has experience on JavaScript knows well that multiplication in JavaScript are calculated according to UK-US number formatting.

Let me explain further, you are making an e-commerce site where the server number formatting is set to EU culture. You calculate the price which is multiplication of the product and the quantity, in JavaScript and posted it without any validation. Bam. You just made the client pay 100 times more than the real price (if there is 2 decimal points)

In EU numeric system, the server takes 18599.00 instead of 185.99 when you post. So you should be careful about this.

So what could we do then?

Changing JavaScript Numbers into Different Local Value Format

We should not directly post the values we get with JavaScript operations before converting it to local formatting. This can be achieved in two ways:

1. Converting number into a string

We can convert the number we get to the string in the format we want. We can use different methods like "toLocaleString()" or "replace()" for these operations.

var number = 159.89; 
console.log(number); // 159.89
console.log(number.toLocaleString()) // in EU system "159,89" in UK-US system "159.89"
console.log(number.toString().replace('.',',')) // "159,89"

Let's get to the point

2. Localizing the number with Intl

The practical and stable solution for converting to local formatting is the Intl library used in EcmaScript5 and later versions. I like this library very much as it does all the job.

var number = 131723.56
console.log(new Intl.NumberFormat('de-DE').format(number)) // 131.723,56
console.log(Intl.NumberFormat('tr-TR', { style: 'currency', currency: 'TRY' }).format(number)) // ₺131.723,56
console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number)); // 1,32,000

It takes country code as the first parameter. It is also possible to change the format with customized configurations as the second optional parameter.

Currency result gives us the value by putting the currency sign in front of it and changing the "." and "," according to the culture.

As a result, if you are working with different cultures and number formattings I Strongly recommend you to use this library rather than struggling with string. With Intl library, you can localize any value like date, number, currency etc.

I'd be happy if I contributed to your knowledge or refresh the information of yours

Happy coding you all