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

前端 未结 6 1916
無奈伤痛
無奈伤痛 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:15

    For number type textbox

    Append .00 if number present

    function addZeroes(ev) {
        debugger;
        // Convert input string to a number and store as a variable.
        var value = Number(ev.value);
        // Split the input string into two arrays containing integers/decimals
        var res = ev.value.split(".");
        // If there is no decimal point or only one decimal place found.
        if (res.length == 1 || res[1].length < 3) {
            // Set the number to two decimal places
            value = value.toFixed(2);
        }
        // Return updated or original number.
        if (ev.value != "") {
            ev.value = String(value);
        }
    }

提交回复
热议问题