Add .00 (toFixed) only if number has less than two decimal places

前端 未结 6 1915
無奈伤痛
無奈伤痛 2020-12-29 20:47

I need to add zeroes, so that each number has at least two decimals, but without rounding. So for example:

5      --> 5.00
5.1    --> 5.10
5.11   --&g         


        
6条回答
  •  失恋的感觉
    2020-12-29 21:07

    The below code provides one way to do what you want. There are others.

    function addZeroes(num) {
        // Cast as number
        var num = Number(num);
        // If not a number, return 0
        if (isNaN(num)) {
            return 0;
        }
        // If there is no decimal, or the decimal is less than 2 digits, toFixed
        if (String(num).split(".").length < 2 || String(num).split(".")[1].length<=2 ){
            num = num.toFixed(2);
        }
        // Return the number
        return num;
    }
    
    console.log(addZeroes(5)); // Alerts 5.00
    console.log(addZeroes(5.1)); // Alerts 5.10
    console.log(addZeroes(5.11)); // Alerts 5.11
    console.log(addZeroes(5.111)); // Alerts 5.111
    

    http://jsfiddle.net/nzK4n/

提交回复
热议问题