1. 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?

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

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

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

5. Instead of using parseInt or parseFloat you can use Number().
Code JavaScript:
```<script type="text/javascript">

var str = '08';

var num = Number(str);

</script>```

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

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

8. Originally Posted by webdev1958
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.
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.

9. Using the + works but can be confusing for noobies if not used properly
Code:
```<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.

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•