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?
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?
Share edited Feb 2, 2015 at 23:06 Jesse Jashinsky 10.7k6 gold badges41 silver badges64 bronze badges asked Jan 3, 2015 at 9:26 Staunton AllenStaunton Allen 772 silver badges11 bronze badges 1-
You might also find 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. ;-) – RobG Commented Jan 3, 2015 at 10:29
4 Answers
Reset to default 4Try to use parseFloat()
instead of parseInt()
Also use <script type="text/javascript">
instead of <script language="javascript">
that will be more standard and correct
parseInt will convert any decimal to an integer so parseInt(1.5)
bees 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;
}
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.
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>