Formatting a number with exactly two decimals in JavaScript

后端 未结 30 2220
广开言路
广开言路 2020-11-21 06:29

I have this line of code which rounds my numbers to two decimal places. But I get numbers like this: 10.8, 2.4, etc. These are not my idea of two decimal places so how I can

相关标签:
30条回答
  • 2020-11-21 07:04
    Number(Math.round(1.005+'e2')+'e-2'); // 1.01
    

    This worked for me: Rounding Decimals in JavaScript

    0 讨论(0)
  • 2020-11-21 07:04

    Round down

    function round_down(value, decPlaces) {
        return Math.floor(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
    }
    

    Round up

    function round_up(value, decPlaces) {
        return Math.ceil(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
    }
    

    Round nearest

    function round_nearest(value, decPlaces) {
        return Math.round(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
    }
    

    Merged https://stackoverflow.com/a/7641824/1889449 and https://www.kirupa.com/html5/rounding_numbers_in_javascript.htm Thanks them.

    0 讨论(0)
  • 2020-11-21 07:04

    Simple as this.

    var rounded_value=Math.round(value * 100) / 100;
    
    0 讨论(0)
  • 2020-11-21 07:05
    Number(((Math.random() * 100) + 1).toFixed(2))
    

    this will return a random number from 1 to 100 rounded to 2 decimal places.

    0 讨论(0)
  • 2020-11-21 07:06
    (Math.round((10.2)*100)/100).toFixed(2)
    

    That should yield: 10.20

    (Math.round((.05)*100)/100).toFixed(2)
    

    That should yield: 0.05

    (Math.round((4.04)*100)/100).toFixed(2)
    

    That should yield: 4.04

    etc.

    0 讨论(0)
  • 2020-11-21 07:07

    Using this response by reference: https://stackoverflow.com/a/21029698/454827

    I build a function to get dynamic numbers of decimals:

    function toDec(num, dec)
    {
            if(typeof dec=='undefined' || dec<0)
                    dec = 2;
    
            var tmp = dec + 1;
            for(var i=1; i<=tmp; i++)
                    num = num * 10;
    
            num = num / 10;
            num = Math.round(num);
            for(var i=1; i<=dec; i++)
                    num = num / 10;
    
            num = num.toFixed(dec);
    
            return num;
    }
    

    here working example: https://jsfiddle.net/wpxLduLc/

    0 讨论(0)
提交回复
热议问题