Staunton Allen
Staunton Allen

Reputation: 77

Calculate parseint with decimal

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?

Upvotes: 0

Views: 4176

Answers (4)

KooiInc
KooiInc

Reputation: 122898

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>

Upvotes: 1

scripni
scripni

Reputation: 2164

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.

Upvotes: 1

Wayne Ellery
Wayne Ellery

Reputation: 7958

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;
}

Upvotes: 1

Max Leps
Max Leps

Reputation: 479

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

Upvotes: 4

Related Questions