I am converting seconds to years and months as follows:
var seconds = 1;
var years = parseInt((((seconds / 60) / 60) / 24) / 365);
var months = parseInt((((seconds / 60) / 60) / 24) / 30);
alert('Years: ' + years + ', ' + 'Months: ' + months);
I would expect the above to return 0 for years and months values, however it returns 3. The years value seems to be returning wrong for seconds values less than 32. And the months value seems to be returning wrong for seconds values less than 4.
Isn’t 0 the nearest integer to 3.170979198376459e-8? Why does it return 3?
Here is my logic: 1 seconds is 0 years. Is that flawed?
I am not specifically converting 1 seconds to years, it is more like an input box and when I enter anything less than 31536000 seconds, it should display 0 for years. It doesn’t when I enter a value less than 32.
Now I can put some “if” check to fix that but I shouldn’t have needed that.
Thanks for the input. I need integer results, not floating numbers. parseInt is what I need in my case, it just doesn’t return correct values for very small numbers like 3.170979198376459e-8 etc. It should return 0, but it returns 3.
Because 3.170979198376459e-8 is a number and parseInt expects a string to be passed.
> console.log(typeof 3.1709791983764586e-8);
number
As mentioned in the docs for parseInt if the passed value is not a string then it is converted to one. In effect you are going the following.
> parseInt("3.1709791983764586e-8");
3
The reason it outputs 3 is explained in the docs. Emphases is mine.
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.
Thanks a lot, it appears that is what I should have used. Works perfectly fine now!
To answer your question: Usually, when you try to fix something that is not supposed to do what you are trying to do, you get blinded to other options.
You are using the wrong function - parseInt expects integer input in a base between 2 and 36 and converts it to base 10 whereas what you are supplying isn’t an integer in any number base.
For some unknown reason only the first couple of replies displayed when I first saw this thread. I didn’t see any of the answers that explained how to solve it properly. If I had then I wouldn’t have repeated what had already been said.