JavaScript Number.toLocaleString() with 4 digits after separator

后端 未结 5 1029
长情又很酷
长情又很酷 2020-12-16 09:03

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

Example:

var number = 49.9712;
document.getElementById(\'id         


        
相关标签:
5条回答
  • 2020-12-16 09:23

    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);
    }
    
    0 讨论(0)
  • 2020-12-16 09:25

    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.

    0 讨论(0)
  • 2020-12-16 09:26

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

    number.toLocaleString(undefined, { minimumFractionDigits: 4 })
    
    0 讨论(0)
  • 2020-12-16 09:39

    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();
    
    0 讨论(0)
  • 2020-12-16 09:44

    If you need to use Locale settings than I don't think you'll be able to specify that you need 4 decimal places, but you can obviously do this using other prototype methods, such as toFixed().

    Here's an example:

    var number = 12.3456
    number.toFixed(4)
    
    0 讨论(0)
提交回复
热议问题