71

Is there a way to get number.toLocaleString() with 4 digits after the comma?

Example:

var number = 49.9712;
document.getElementById('id').innerText = number.toLocaleString();

Result: 49,9712

But now it always returns number with 2 digits after comma: 49,97

reformed
  • 4,205
  • 10
  • 58
  • 83
Artem
  • 1,767
  • 1
  • 11
  • 19

4 Answers4

137

You may use second argument to provide some options. In your case, with default locale:

number.toLocaleString(undefined, { minimumFractionDigits: 4 })
Radagast
  • 5,352
  • 3
  • 21
  • 18
  • 3
    Great! I didn't know that method had an options parameter. – luis.ap.uyen Jun 14 '16 at 13:58
  • 6
    Thank you. It seems like the ONLY possible solution when formatting numbers under a user locale with a defined number digits after the separator. As for myself, I used a second parameter named maximumFractionDigits. It forces the number to be outputted with the specified number of fraction digits. – David Jul 19 '16 at 17:32
  • very smooth and easy to use. – ParisNakitaKejser Jun 20 '18 at 13:06
  • 3
    If you only use minimumFractionDigits, you can get more digits than 4. There is a maximumFractionDigits field too - see comment in question. – Dean Dec 19 '18 at 21:38
16

I found that

var number = 49.9712;
number.toLocaleString( { minimumFractionDigits: 4 })

gave the result of "49.971"

In order to actually get the 4 decimal place digits, I did this:

number.toLocaleString(undefined, { minimumFractionDigits: 4 })

Also filling in a country code worked:

number.toLocaleString('en-US', { minimumFractionDigits: 4 })

In both cases I got 49.9712 for the answer.

rainslg
  • 375
  • 4
  • 11
0

Quick solution:

call it like this:

console.log(localeN(value, 4));
function localeN(v, n) {
    var i, f;
  
    i = Math.floor(v);
    f = v - i;
    return i.toLocaleString() + f.toFixed(n).substr(1);
}
-3

You cannot do this with toLocaleString() alone. But you can round to 4 decimal places before displaying:

var n = Math.round(number * 10000) / 10000;
document.getElementById('id').innerText = n.toLocaleString();
Christophe
  • 356
  • 3
  • 16