# parseInt('08') == 0

I assume it’s treating it as octal and 8 therefore is an invalid character. However, I need to take the string ‘08’ and convert it to decimal 8.

Am I going to have to remove leading zeroes from the string? There must be a better way, surely?

Using the + works but can be confusing for noobies if not used properly

<script type="text/javascript">

var num = 23;
var str2 = '08';

</script>

I’m going to stick with using Number() since the extra few characters is no big deal. Putting a + infront of a string doesn’t make sense semantically to me either.

That’s why I suggested the + method as the better one to use - you can consider the + in front of a string (but with no other number or variable in front of it to represent Number() as it does the same thing.

There’s a shorter way to convert a string to a number:

num = +str;

Simply adding a + to the front of the string variable name forces the same conversion that Number() does.

Other alternatives are to add *1, /1 or -0 after the string variable name.

I used to multiply by 1 as well early on until I became aware of other ways.

Sure, they work and do what you want, but imho multiplying a string by a number looks a bit like a hack and “amateurish” since multiplying a string by a number doesn’t make sense semantically to me.

Instead of using parseInt or parseFloat you can use Number().

<script type="text/javascript">

var str = '08';

var num = Number(str);

</script>

parseInt(‘08’,10)// returns 8

//convert a string to its leading decimal integer equivilent.

parseFloat(‘08’)// returns 8

// convert a string to its lrading decimal equivilent

If you specify a second parameter into parseInt (of between 2 and 36) then the number in the first parameter will be assumed to be in that number base. The purpose of parseInt is to convert numbers from other number bases to base 10.

If you don’t specify a second parameter then if the number starts with 0x it will be assumed to be base 16 and if it starts with 0 not followed by an x then some browsers will assume it is base 8.

Ah thanks, I guessed it was seeing it as octal but didn’t know how to prevent it. Thanks