JavaScript Number.toLocaleString() with 4 digits after separator

JavascriptNumbersFormat

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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);
}

Solution 4 - Javascript

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();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArtemView Question on Stackoverflow
Solution 1 - JavascriptRadagastView Answer on Stackoverflow
Solution 2 - JavascriptrainslgView Answer on Stackoverflow
Solution 3 - Javascriptuser2430829View Answer on Stackoverflow
Solution 4 - JavascriptChristopheView Answer on Stackoverflow