Formatting a number with exactly two decimals in JavaScript

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

    With these examples you will still get an error when trying to round the number 1.005 the solution is to either use a library like Math.js or this function:

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

提交回复
热议问题