Monday, February 11, 2013

The DANGER Behind parseInt function - Javascript


SCENARIO:

Inside a certain if condition, I used parseInt('08')to convert a string to its equivalent numerical value. But unexpectedly, it returned 0 as a result.

I also tried:

parseInt('01')
parseInt('02')
parseInt('03')
parseInt('04')
parseInt('05')
parseInt('06')
parseInt('07')
parseInt('08')
parseInt('09')

but all of which returned the expected result except for 8 and 9 which resulted to 0.


SOLUTION: 
The parseInt()javascript method is an octal base function (i.e. it can only cope up with input from string of 0 to 7). In solving this, we can either include the base or use Number() function as an alternative.


1. Using base of decimal number system:

parseInt('08', 10); 
//wherein 10 signifies the base value of decimal number system


2. Using Number() function.


No comments:

Post a Comment