Format number to always show 2 decimal places

前端 未结 30 2827
爱一瞬间的悲伤
爱一瞬间的悲伤 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:41
    var quantity = 12;
    
    var import1 = 12.55;
    
    var total = quantity * import1;
    
    var answer = parseFloat(total).toFixed(2);
    
    document.write(answer);
    
    0 讨论(0)
  • 2020-11-21 08:42

    A much more generic solution for rounding to N places

    function roundN(num,n){
      return parseFloat(Math.round(num * Math.pow(10, n)) /Math.pow(10,n)).toFixed(n);
    }
    
    
    console.log(roundN(1,2))
    console.log(roundN(1.34,2))
    console.log(roundN(1.35,2))
    console.log(roundN(1.344,2))
    console.log(roundN(1.345,2))
    console.log(roundN(1.344,3))
    console.log(roundN(1.345,3))
    console.log(roundN(1.3444,3))
    console.log(roundN(1.3455,3))
    
    Output
    
    1.00
    1.34
    1.35
    1.34
    1.35
    1.344
    1.345
    1.344
    1.346
    
    0 讨论(0)
  • 2020-11-21 08:42

    Try below code:

    function numberWithCommas(number) { 
    
       var newval = parseFloat(Math.round(number * 100) / 100).toFixed(2);
    
       return newval.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    
    0 讨论(0)
  • 2020-11-21 08:43

    For the most accurate rounding, create this function:

    function round(value, decimals) {
        return Number(Math.round(value +'e'+ decimals) +'e-'+ decimals).toFixed(decimals);
    }
    

    and use it to round to 2 decimal places:

    console.log("seeked to " + round(1.005, 2));
    > 1.01
    

    Thanks to Razu, this article, and MDN's Math.round reference.

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

    here is another solution to round only using floor, meaning, making sure calculated amount won't be bigger than the original amount (sometimes needed for transactions):

    Math.floor(num* 100 )/100;
    
    0 讨论(0)
  • 2020-11-21 08:47
    (num + "").replace(/^([0-9]*)(\.[0-9]{1,2})?.*$/,"$1$2")
    
    0 讨论(0)
提交回复
热议问题