Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use toLocaleString() and tofixed(2) in JavaScript

Tags:

javascript

How can I do this in JavaScript?

var num = 2046430;  num.toLocaleString();  will give you "2,046,430"; 

What I have tried is:

var num = 2046430;  num.toLocaleString().toFixed(2); 

Expected Output

"2,046,430.00"

like image 549
Question User Avatar asked Jul 23 '15 07:07

Question User


People also ask

What does the toLocaleString () method do in JS?

The toLocaleString() method returns a string with a language-sensitive representation of this date. In implementations with Intl. DateTimeFormat API support, this method simply calls Intl. DateTimeFormat .

How do I localize a number in JavaScript?

In JavaScript, toLocaleString() is a Number method that is used to convert a number into a locale-specific numeric representation of the number (rounding the result where necessary) and return its value as a string.


1 Answers

Taken from MDN:

Syntax

numObj.toLocaleString([locales [, options]])

toLocaleString takes 2 arguments. The first is the locale, the second are the options. As for the options, you are looking for:

minimumFractionDigits

The minimum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number and percent formatting is 0; the default for currency formatting is the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information).

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

To be able to set the options without setting the locale, you can pass undefined as first argument:

var num = 2046430; num.toLocaleString(undefined, {minimumFractionDigits: 2}) // 2,046,430.00 

However this also allows the fraction to be longer than 2 digits. So we need to look for one more option called maximumFractionDigits. (Also on that MDN page)

var num = 2046430.123; num.toLocaleString(undefined, {   minimumFractionDigits: 2,   maximumFractionDigits: 2 }) // 2,046,430.12 
like image 66
Sebastian Nette Avatar answered Oct 15 '22 20:10

Sebastian Nette