parseFloat rounding

JB. picture JB. · Jan 9, 2011 · Viewed 73.7k times · Source

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

Answer

moinudin picture moinudin · Jan 9, 2011

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