Formatting a number with exactly two decimals in JavaScript

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

    This is very simple and works just as well as any of the others:

    function parseNumber(val, decimalPlaces) {
        if (decimalPlaces == null) decimalPlaces = 0
        var ret = Number(val).toFixed(decimalPlaces)
        return Number(ret)
    }
    

    Since toFixed() can only be called on numbers, and unfortunately returns a string, this does all the parsing for you in both directions. You can pass a string or a number, and you get a number back every time! Calling parseNumber(1.49) will give you 1, and parseNumber(1.49,2) will give you 1.50. Just like the best of 'em!

提交回复
热议问题