1
I have a setInterval
running every second calling a function myTimer
which adds 0.1 to a total value and shows on screen.
É suposto ir 0.1->0.2->0.3->0.4->0.5->...
But it’s going 0.1->0.2000004->0.3->0.4->0.49999999->0.6->... (example, it doesn’t always make the same rounding and the same instants)
You’re not doing the right math, you’re adding roundups of 0.1 sometimes.
Code:
<div id="total"></div>
<script>
var myVar = setInterval(myTimer, 1000);
var total = 0;
function myTimer() {
document.getElementById("total").innerHTML = total;
total = total + 0.1;
}
</script>
Jsfiddle: https://jsfiddle.net/se2xt9ma/1/
Some way to fix this mistake or some reason to be happening?
I had tried to add
total = total.toFixed(1) ;
but didn’t do the math, didn’t know it converted into String. Thanks for the solution.– Pbras
You’re welcome @Pbras :)
– Afonso