parseFloat rounding

家住魔仙堡 提交于 2019-11-27 08:33:32
marcog

Use toFixed() to round num to 2 decimal digits using the traditional rounding method. It will round 4.050000000000001 to 4.05.

num.toFixed(2);

You might prefer using toPrecision(), which will strip any resulting trailing zeros.

Example:

1.35+1.35+1.35 => 4.050000000000001
(1.35+1.35+1.35).toFixed(2)     => 4.05
(1.35+1.35+1.35).toPrecision(3) => 4.05

// or...
(1.35+1.35+1.35).toFixed(4)     => 4.0500
(1.35+1.35+1.35).toPrecision(4) => 4.05

Reference: JavaScript Number Format - Decimal Precision

var num = 4.050000000000001;

num = num.toFixed(2);

toFixed will round up depending on how many digits after the decimal you're looking for.

You can use Math.round(total*100000000000)/100000000000; in the code. It will work for most of the cases

This works:

$(document).ready(
    function() {
            $('#field1').blur(function(){ $('#field2').val(parseFloat($(this).val() * 2.2).toFixed(1)); });
            $('#field2').blur(function(){ $('#field1').val(parseFloat($(this).val() / 2.2).toFixed(1)); });
    }
);

This fails:

$(document).ready(
    function() {
            $('#field1').blur(function(){ $('#field2').val(parseFloat($(this).val() * 2.2)).toFixed(1); });
            $('#field2').blur(function(){ $('#field1').val(parseFloat($(this).val() / 2.2)).toFixed(1); });
    }
);

So be careful the way you place your parenthesis ()... In first case, the rounding will work, but won't work in the second one...

Instead of rounding, you may want to use the port of Java's BigDecimal to get actually precise decimal math.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!