Formatting a number with exactly two decimals in JavaScript

后端 未结 30 3044
广开言路
广开言路 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 06:42

    I usually add this to my personal library, and after some suggestions and using the @TIMINeutron solution too, and making it adaptable for decimal length then, this one fits best:

    function precise_round(num, decimals) {
       var t = Math.pow(10, decimals);   
       return (Math.round((num * t) + (decimals>0?1:0)*(Math.sign(num) * (10 / Math.pow(100, decimals)))) / t).toFixed(decimals);
    }
    

    will work for the exceptions reported.

提交回复
热议问题