As with most things, there are several ways to do this conversion. I’ve used parseInt() a lot in the past to convert a string into a number (although strictly speaking I am converting to an Integer rather than just a Number when using parseInt()), but recently ran into some strange behaviour that I wanted to understand.
var l_sValue = "07"; alert(parseInt(l_sValue)); // alerts 7
This seems to work fine, the string represents the number 7, and the parseInt() correctly parses it into the integer 7. Now we change the string value and something strange occurs:
var l_sValue = "08"; alert(parseInt(l_sValue)); // alerts 0
This is obviously not the expected result! The solution is to use parseInt() correctly, and pass through both parameters (the second parameter is the number base to use).
- the string starts with ‘0′, then it will default to base 8 (octal)
- the string starts with ‘0x’, then it will default to base 16 (hexadecimal)
Now look what happens when we pass in the second parameter and use (the more familiar) base 10:
var l_sValue = "08"; alert(parseInt(l_sValue, 10)); // alerts 8
Lesson for the day: always pass in the base when using parseInt() to parse a string into an integer.