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
You can use Math.round(total*100000000000)/100000000000;
in the code. It will work for most of the cases
Instead of rounding, you may want to use the port of Java's BigDecimal to get actually precise decimal math.
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...
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.