Saturday, August 13, 2016

JavaScript parseInt('08') Returns Zero

Recently in one of our product we faced strange issue related to date display.  We were passing date components to display like this.

1st August 2016

Everything was working fine, till we faced the issue since start of Month of August. Instead of displaying correct date it was displaying 1 year old date or any random date.

It took sometime for me to figure out issue. Issue was number system. When we parse as following

parseInt("08")

In some browser or some android phones, it is considered as octal number and octal number system is used to parse. So "08" is "0" in octal so it gives wrong number.

So to fix this issue you can either use radix parameter in parseInt

parseInt("08", 10);

Here radix 10 represent decimal number system so "08" is parsed as "8" Other solution is to use Number function to parse the string.

Number("08");

And it gives you correct result. Octal system is deprecated in most of the browser now but still some old browser and some android phones are still using it so we have to to use above methods to avoid any issue.

Hope this helps you.

No comments:

Post a Comment