77

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,505
  • 11
  • 62
  • 88
Artem
  • 1,937
  • 1
  • 14
  • 19

4 Answers4

155

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

number.toLocaleString(undefined, { minimumFractionDigits: 4 })
Radagast
  • 5,798
  • 3
  • 22
  • 18
  • 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
  • 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
  • Use `maximumFractionDigits: 0` if you don't want any fractional part. For example, ```console.log(function a(ms){return `${((ms/1000)%60).toLocaleString('en-AU',{minimumIntegerDigits: 2, maximumFractionDigits: 0})}d:${((ms/1000/60)%60).toLocaleString('en-AU',{minimumIntegerDigits: 2, maximumFractionDigits: 0})}:${((ms/24/60/60/1000)).toLocaleString('en-AU',{maximumFractionDigits: 0})}s`}(45*24*60*60*1000 + 4255325))```. This will produce `45d:11m:55s` – Tom Anderson Apr 18 '23 at 06:21
19

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
  • 415
  • 5
  • 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);
}
-4

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
  • 354
  • 3
  • 16