Adding 0.1 to a setInterval gives rounding problems

Asked

Viewed 28 times

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?

2 answers

1

This is normal, the cause of this is that floating point is represented internally in binary, and 0.1 is a periodic binary titer. Some simple solutions you can adopt:

1) increment 'total' from 1 to 1, dividing by 10 only when displaying or using the value.

2) increment by a fractional value that has exact binary representation, for example 0.125. In this case you would have to change the tempo of the timer to 125ms, too.

1


Here is an example of a method you can use:

.toFixed()

<div id="total">
</div>

var myVar = setInterval(myTimer, 1000);
var total = 0;
function myTimer() {
    document.getElementById("total").innerHTML = total.toFixed(1);
    total = total + 0.1;
}

toFixed() converts a number to a string, in this case with 1 decimal.

Jsfiddle: https://jsfiddle.net/1Lhm7qjf/

  • 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.

  • You’re welcome @Pbras :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.