Formatting a number with exactly two decimals in JavaScript

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

    I don't know why can't I add a comment to a previous answer (maybe I'm hopelessly blind, dunno), but I came up with a solution using @Miguel's answer:

    function precise_round(num,decimals) {
       return Math.round(num*Math.pow(10, decimals)) / Math.pow(10, decimals);
    }
    

    And its two comments (from @bighostkim and @Imre):

    • Problem with precise_round(1.275,2) not returning 1.28
    • Problem with precise_round(6,2) not returning 6.00 (as he wanted).

    My final solution is as follows:

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

    As you can see I had to add a little bit of "correction" (it's not what it is, but since Math.round is lossy - you can check it on jsfiddle.net - this is the only way I knew how to "fix" it). It adds 0.001 to the already padded number, so it is adding a 1 three 0s to the right of the decimal value. So it should be safe to use.

    After that I added .toFixed(decimal) to always output the number in the correct format (with the right amount of decimals).

    So that's pretty much it. Use it well ;)

    EDIT: added functionality to the "correction" of negative numbers.

提交回复
热议问题