20

    <head>
    <script>
        window.setInterval(function(){timer()},100);
        function timer()
            {
                document.getElementById("timer").innerHTML=
               (parseInt(document.getElementById("timer").innerHTML*100)+1)/100;
            }
    </script>
    </head>
    <body>
        <div id="timer">0.000</div>
    </body>

As you see, timer counts only up to 0.29.

Why is it?

nicael
  • 18,550
  • 13
  • 57
  • 90

1 Answers1

25

It's because of the way floating point math works coupled with your parseInt(). Refer to Is floating point math broken.

When it reaches 0.29, it does 0.29 x 100, which you're expecting to result in 29 but actually it is:

console.log(0.29 * 100);
28.999999999999996

Next, you convert it to an integer using parseInt() which results in 28 (removing all of the decimal places), finally you add 1 and divide by 100 making the result 0.29 and this is repeated on each tick of the timer, the number can't increase.

It would be better to store the raw value as a variable and output it using .toFixed(2), instead of using the number on the UI as the source. Like this:

Fiddle

var num = 0.00;

window.setInterval(function () {
    timer();
}, 100);

function timer() {
    num = ((num * 100) + 1) / 100;
    document.getElementById("timer").innerHTML = num.toFixed(2);
}
Community
  • 1
  • 1
MrCode
  • 63,975
  • 10
  • 90
  • 112
  • It should also be noted that `parseInt` is redundant because `*` casts to numeric anyway (and in this case the function is harmful) – Niet the Dark Absol May 09 '14 at 16:27
  • 2
    `parseInt` isn't redundant here, it is the source of the problem because it removes the decimal places which ultimately causes the number to stick at `0.29`. If you remove the `parseInt()`, the counter continues beyond `0.29` (albeit showing the full decimal places). – MrCode May 09 '14 at 16:31
  • Its use is misguided because the thing being parsed is already a number. Anyway, missing the point ;) – Niet the Dark Absol May 09 '14 at 16:32
  • Yes it is already a number, but a float not an int. If it was `parseFloat()` then it would be completely redundant. – MrCode May 09 '14 at 16:34
  • As far as the logic goes, `x.innerHTML*100` was *supposed* to be an int (obviously it isn't due to float errors) and yet was still being passed to `parseInt`. – Niet the Dark Absol May 09 '14 at 16:39
  • Agreed, in OP's mind it was supposed to be an int :) – MrCode May 09 '14 at 17:03
  • @MrCode - +1 This kind of bug is so common. – Les May 22 '14 at 18:39