Home>

i want to solve a strange value when calculating a large number with javascript

When you press the start button in view, the time is saved in localstorage and the timer function is called. Since the timer function is continuously called every second with setTimeout, console is displayed as 1,2,3… by console.log (elapsed) ;.

The value is calculated by dividing 31536000 (seconds of a year) from the elapsed seconds to get the elapsed years from that elapsed time.

I want to solve is press the start button and check the output of console.log (year);After pressing the start button, the first 3,6,9 and multiples of 3 are displayed. 1,2,2,2,3,3,3 ... and so on. I would like to solve the problem that when I press the start button, a strange value appears even though 0,0,0,0 must be displayed from the beginning.

timer.js
``````function timer () {
now = new Date ();
// Elapsed time (seconds)
elapsed = parseInt ((now.getTime ()-localStorage.getItem ("time"))/1000);
console.log (elapsed);
year = parseInt (elapsed/31536000);
console.log (year);
if (localStorage.getItem ("time")) {
var id = setTimeout ("repetition ()", 1000);
}
}``````

I thought that the numerical value (31536000) was too large to give an accurate value, so when dividing by 31536, it was calculated well and 0 has been output since the start button was pressed.

Also, instead of suddenly writing the year part in seconds, it is a formula for calculating the number of seconds in a year. If i rewrite it as year = parseInt (elapsed/365 * 24 * 60 * 60);1000 or more) was output irregularly.

I didn't know the cause at all. If i have a solution, please let me know.

The cause of this bug is the use of`parseInt`even though the argument is numeric.
In JavaScript, if the value is close to zero, such as`0.000000031709791983764586`, it is converted to a string with an exponential notation such as`3.1709791983764586e-8`.
So, for example,`parseInt (1/31536000)`becomes`parseInt (3.1709791983764586e-8)`and`parseInt ("3.1709791983764586e-8")`and finally`3`.
Bugs can be solved by using`Math.floor`instead of
`parseInt`.