Reliable JS rounding numbers with toFixed(2) of a 3 decimal number

后端 未结 5 1892
野的像风
野的像风 2020-12-11 06:54

I am simply trying to round up 1.275.toFixed(2) and I was expecting a return of 1.28, rather than 1.27.

Using various calculators and t

5条回答
  •  臣服心动
    2020-12-11 07:14

    While I am a little late, this could help someone with the same requirement. If the value is a string, simply add an additional "1" to the end and your issue will be fixed. If input = 10.55 then it would become 10.551 which in turn would become 10.56.

    This example uses jQuery

    function toTwoDecimalPlaces(input) {
            var value = $(input).val();
            if (value != null) {
                value = parseFloat(value + "1").toFixed(2);
            }
            $(input).val(value);
    }
    

    Update: If the input is accepting whole numbers and/or numbers with 1 decimal place, then you will want to check how many decimal places have been used. If it is greater than the fixed amount then add the "1".

    function toTwoDecimalPlaces(input) {
            var value = $(input).val();
            if (value.includes(".")) {
                var splitValue = value.split(".");
                if (splitValue[1].length > 2) {
                    value = parseFloat(value + "1").toFixed(2);
                }
            }
            $(input).val(value);
    }
    

提交回复
热议问题