parseFloat rounding

前端 未结 5 1189
太阳男子
太阳男子 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: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

提交回复
热议问题