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 example. How can I round the total to the second decimal instead of that long string?
The input fields will have more than just the 1.35 example so I need the total to never have more than 2 points after the decimal. Here is the full working code:
<html>
<head>
<script type="text/javascript">
function Calc(className){
var elements = document.getElementsByClassName(className);
var total = 0;
for(var i = 0; i < elements.length; ++i){
total += parseFloat(elements[i].value);
}
document.form0.total.value = total;
}
function addone(field) {
field.value = Number(field.value) + 1;
Calc('add');
}
</script>
</head>
<body>
<form name="form0" id="form0">
1: <input type="text" name="box1" id="box1" class="add" value="0" onKeyUp="Calc('add')" onChange="updatesum()" onClick="this.focus();this.select();" />
<input type="button" value=" + " onclick="addone(box1);">
<br />
2: <input type="text" name="box2" id="box2" class="add" value="0" onKeyUp="Calc('add')" onClick="this.focus();this.select();" />
<input type="button" value=" + " onclick="addone(box2);">
<br />
<br />
Total: <input readonly style="border:0px; font-size:14; color:red;" id="total" name="total">
<br />
</form>
</body></html>
Some things I have tried, which should work but I am clearly implementing them incorrectly:
for(var i = 0; i < elements.length; ++i){
total += parseFloat(elements[i].value.toString().match(/^\d+(?:\.\d{0,2})?/));
var str = total.toFixed(2);
or
for(var i = 0; i < elements.length; ++i){
total += parseFloat(elements[i].value * 100) / 100).toFixed(2)
Have also had no luck with Math.floor
This works:
This fails:
So be careful the way you place your parenthesis ()... In first case, the rounding will work, but won't work in the second one...
You can use
Math.round(total*100000000000)/100000000000;
in the code. It will work for most of the casesUse
toFixed()
to roundnum
to 2 decimal digits using the traditional rounding method. It will round 4.050000000000001 to 4.05.You might prefer using
toPrecision()
, which will strip any resulting trailing zeros.Example:
Reference: JavaScript Number Format - Decimal Precision
Instead of rounding, you may want to use the port of Java's BigDecimal to get actually precise decimal math.
toFixed
will round up depending on how many digits after the decimal you're looking for.