Welcome to Code Couch

# Tips on converting strings into numbers

Posted by at 10:26am on August 6, 2007.

When you are reading a value from a text input, the value is returned as a string. This is not really a problem for Javascript in that it’s loosely typed and converting the string into a number is really straightforward.

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).

If you do not pass in the second parameter (the base, or radix) then Javascript will default to base 10, unless:

• 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)

Because the string we used above started with ‘0′, Javascript defaulted to use base 8. The reason we see 0 being returned from parseInt(’08′) is because 8 is not a valid number in octal (we would count in octal 0, 1, 2, … 6, 7, 10, 11, 12, … 17, 20, 21, …).

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.

Tags: