Search code examples
javascriptparsingdecimalparseint

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?


Solution

  • 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