It's Khayer, Bangladesh


Javascript string to integer conversion hell
February 9, 2012, 8:57 pm
Filed under: Javascript | Tags: , , ,

Javascript is great. But some over intelligency cause also great problem to the developer.

Here I give some string to integer conversion result in JavaScript,

1.  parseInt(“01″)=>1

2.  parseInt(“05″)=>5

3.  parseInt(“08″)=>0

4.  parseInt(“09″)=>0

 

Here javascript is giving wrong result for 3 and 4.

Problem:

When javascript get Zero leading string as parseInt parameter, it takes 8 base system for conversion automatically instead of 10 base.

Solution:

Simply set the base explicitly like below,

3. parseInt(“08″,10)=>8

4. parseInt(“09″,10)=>9

It is best practice in javascript to set the conversion “base” during any type number parsing.

 




Follow

Get every new post delivered to your Inbox.