Format number to always show 2 decimal places

前端 未结 30 2826
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 08:17

I would like to format my numbers to always display 2 decimal places, rounding where applicable.

Examples:

number     display
------     -------
1            


        
相关标签:
30条回答
  • 2020-11-21 08:31

    function number_format(string,decimals=2,decimal=',',thousands='.',pre='R$ ',pos=' Reais'){
      var numbers = string.toString().match(/\d+/g).join([]);
      numbers = numbers.padStart(decimals+1, "0");
      var splitNumbers = numbers.split("").reverse();
      var mask = '';
      splitNumbers.forEach(function(d,i){
        if (i == decimals) { mask = decimal + mask; }
        if (i>(decimals+1) && ((i-2)%(decimals+1))==0) { mask = thousands + mask; }
        mask = d + mask;
      });
      return pre + mask + pos;
    }
    var element = document.getElementById("format");
    var money= number_format("10987654321",2,',','.');
    element.innerHTML = money;
    #format{
    display:inline-block;
    padding:10px;
    border:1px solid #ffffd;
    background:#f5f5f5;
    }
    <div id='format'>Test 123456789</div>

    0 讨论(0)
  • 2020-11-21 08:32
    var num = new Number(14.12);
    console.log(num.toPrecision(2));//outputs 14
    console.log(num.toPrecision(3));//outputs 14.1
    console.log(num.toPrecision(4));//outputs 14.12
    console.log(num.toPrecision(5));//outputs 14.120
    
    0 讨论(0)
  • 2020-11-21 08:33

    Here's also a generic function that can format to any number of decimal places:

    function numberFormat(val, decimalPlaces) {
    
        var multiplier = Math.pow(10, decimalPlaces);
        return (Math.round(val * multiplier) / multiplier).toFixed(decimalPlaces);
    }
    
    0 讨论(0)
  • 2020-11-21 08:34

    This answer will fail if value = 1.005.

    As a better solution, the rounding problem can be avoided by using numbers represented in exponential notation:

    Number(Math.round(1.005+'e2')+'e-2'); // 1.01
    

    Cleaner code as suggested by @Kon, and the original author:

    Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces)
    

    You may add toFixed() at the end to retain the decimal point e.g: 1.00 but note that it will return as string.

    Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces).toFixed(decimalPlaces)
    

    Credit: Rounding Decimals in JavaScript

    0 讨论(0)
  • 2020-11-21 08:34

    Just run into this one of longest thread, below is my solution:

    parseFloat(Math.round((parseFloat(num * 100)).toFixed(2)) / 100 ).toFixed(2)
    

    Let me know if anyone can poke a hole

    0 讨论(0)
  • Are you looking for floor?

    var num = 1.42482;
    var num2 = 1;
    var fnum = Math.floor(num).toFixed(2);
    var fnum2 = Math.floor(num2).toFixed(2);
    alert(fnum + " and " + fnum2); //both values will be 1.00
    
    0 讨论(0)
提交回复
热议问题