Saturday 28 December 2019

jquery - Floating number in JavaScript timer doesn't increase correctly





I want a little timer which increases with the help of setInterval() the number in a html container.
My code looks like this (jsfiddle):



var currentTime = 0;

window.setInterval(timer, 100)

function timer() {
currentTime = currentTime + 0.1;
$('#time').text(currentTime);

}


Unfortunately this does not only add 0.1 each interval but add 0.1000001 (or something similar). Can someone explain me why?


Answer



Reason: This is because floating point can not be represented accurately in memory. There is always some rounding error.
Solution: You will have to work with integer, and when you have to show the time, divide the integer and then show the value till first digit after the decimal.
Like this:



var currentTime = 0;

window.setInterval(timer, 100)


function timer() {
currentTime = currentTime + 1;
$('#time').text(currentTime / 10);
}


Fiddle: http://jsfiddle.net/2nLAc/1/
Further information: To knwo more about floating points, please see: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...