parseInt question

Hi,

Why is the result of parseInt(“08”) is 0 and not 8?

Thanks

Good question, I had no idea.

If the input string begins with “0”, radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.

I don’t actually use parseInt, I use Number().

What you would actually want to be using is parseFloat as it automatically removes any zero’s proceeding the number you want, see the following jsFiddle to see the result.

Thanks guys!

It was a question that i was asked and it got me confused.

Now jsfiddle is showing 8 for it with default redix. Interesting!!! I am going to spend some more time on it later in the evening.

parseInt is for converting from one number base to another. The second parameter specifies the base of the original number and the result will be base 10. If the second parameter is not specified then vamues starting with 0x will be treated as hexadecimal. If JavaScript is not running in strict mode then some but not all browsers will treat a leading zero as an indication that the numner is octal.

If you are trying to convert a string to a number then a better function to use is Number('08) or even +‘08’