0

I found this in another post:

<script language='javascript'>
function AddInputs()
{
var total = 0;
var coll = document.getElementsByClassName('add')
for ( var i = 0; i<coll.length; i++)
{
    var ele = coll[i];
    total += parseInt(ele.value);
}
var Display = document.getElementById('Display');
Display.innerHTML = total;
}
</script>

It works, but 1.50, 1.50, and 1.50 = 3 which isn't accurate. I'm new to JS (only know PHP), but I looked into it and figure it has something to do with parseInt since 1.50 isn't a whole number. Is there something I can replace parseInt with to calculate it so that the three 1.50 actually equals 4.50?

Jesse Jashinsky
  • 10,313
  • 6
  • 38
  • 63
Staunton Allen
  • 77
  • 2
  • 11
  • You might also find [*convert string to a number in javascript*](http://stackoverflow.com/questions/11613705/convert-string-to-a-number-in-javascript) helpful. And when you discover that `0.1 + 0.2 !== 0.3` you'll want to read the answers to [*Elegant workaround for JavaScript floating point number problem*](http://stackoverflow.com/questions/1458633/elegant-workaround-for-javascript-floating-point-number-problem). ;-) – RobG Jan 03 '15 at 10:29

4 Answers4

4

Try to use parseFloat() instead of parseInt()

Also use <script type="text/javascript"> instead of <script language="javascript"> that will be more standard and correct

Max Leps
  • 469
  • 3
  • 12
  • 1
    The *type* attribute for script elements is optional and defaults to *text/javascript*, so mostly it's not used at all. The language attribute was deprecated in HTML 4 and removed in HTML5. – RobG Jan 03 '15 at 10:30
  • Yes you're right. thanks. script language attribute is wrong anyway. – Max Leps Jan 03 '15 at 10:44
1

parseInt will convert any decimal to an integer so parseInt(1.5) becomes 1. That is why parseInt(1.5) + parseInt(1.5) + parseInt(1.5) = 3. If you want it to equal 4.5 then just replace parseInt with parseFloat:

function AddInputs()
{
  var total = 0;
  var coll = document.getElementsByClassName('add')
  for ( var i = 0; i<coll.length; i++)
  {
    var ele = coll[i];
    total += parseFloat(ele.value);
  }
  var Display = document.getElementById('Display');
  Display.innerHTML = total;
}
Wayne Ellery
  • 7,888
  • 1
  • 28
  • 45
1

When you call parseInt on 1.50 you're getting the integer part of that value (1 in this case). Just replace parseInt with parseFloat and you'll get the value you expect.

scripni
  • 2,144
  • 2
  • 19
  • 25
1

Beside parseFloat you can also use Number to convert a string to a numeric value.

document.querySelector('#add').addEventListener('click', addNumber) 
var total = 0;

function addNumber(e) {
  total += Number(document.querySelector('#plus').value);
  document.querySelector('#result').innerHTML = 'total: '+total.toFixed(2);
}
<input id="plus" type="number" placeholder="type a number"/>

<button id="add">add to total</button>

<div id="result"></div>
KooiInc
  • 119,216
  • 31
  • 141
  • 177