Number Parsing in JavaScript

How many times did you have this in your code:

var str = getSomeNumber(); //say, 1212

var num = parseInt(str);

window.alert('Number is: ' + num);  //Number is: 1212

Nothing special about it... or is it?

It happens that JavaScript's parseInt function is smarter than you think (and, probably, smarter that it should): it tries to interpret the string passed as a parameter and returns the result based on its perceived radix, which may not be 10. An example? Try this:

window.alert('Number is: ' + parseInt('010')); //Number is: 8!!

So, what's the solution? Simply pass the appropriate radix as the second parameter for parseInt:

window.alert('Number is: ' + parseInt('010', 10)); //Number is: 10!! Alright!!

Bookmark and Share

                             

No Comments