Formatting a number with exactly two decimals in JavaScript

后端 未结 30 3148
广开言路
广开言路 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: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/

提交回复
热议问题