Formatting a number with exactly two decimals in JavaScript

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

    You could also use the .toPrecision() method and some custom code, and always round up to the nth decimal digit regardless the length of int part.

    function glbfrmt (number, decimals, seperator) {
        return typeof number !== 'number' ? number : number.toPrecision( number.toString().split(seperator)[0].length + decimals);
    }
    

    You could also make it a plugin for a better use.

提交回复
热议问题