tomb — 2011-08-30T12:28:52-04:00 — #1
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?
system — 2011-09-01T18:22:54-04:00 — #2
Using the + works but can be confusing for noobies if not used properly
var num = 23;
var str2 = '08';
alert(num+str2); //displays 2308
alert(num + +str2); //displays 31
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.
felgall — 2011-09-01T15:15:28-04:00 — #3
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.
felgall — 2011-09-01T03:17:08-04:00 — #4
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.
system — 2011-09-01T03:21:47-04:00 — #5
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.
system — 2011-09-01T00:33:52-04:00 — #6
Instead of using parseInt or parseFloat you can use Number().
var str = '08';
var num = Number(str);
alert(num); // displays 8
mrhoo — 2011-08-30T12:42:19-04:00 — #7
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
felgall — 2011-08-30T15:15:00-04:00 — #8
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.
tomb — 2011-08-31T15:54:12-04:00 — #9
Ah thanks, I guessed it was seeing it as octal but didn't know how to prevent it. Thanks