parseFloat rounding

前端 未结 5 1190
太阳男子
太阳男子 2020-12-01 12:06

I have javascript function that automatically adds input fields together, but adding numbers like 1.35 + 1.35 + 1.35 gives me an output of 4.050000000000001, just as an exam

相关标签:
5条回答
  • 2020-12-01 12:30

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

    0 讨论(0)
  • 2020-12-01 12:32

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

    0 讨论(0)
  • 2020-12-01 12:33

    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...

    0 讨论(0)
  • 2020-12-01 12:39

    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

    0 讨论(0)
  • 2020-12-01 12:39
    var num = 4.050000000000001;
    
    num = num.toFixed(2);
    

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

    0 讨论(0)
提交回复
热议问题