Monday, December 01, 2008

Parse Int problems with leading 0's

Parse Int problems with leading 0's

http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_21701871.html


Trying to convert
string with leading 0 to number and it doesn't work

ie:

var test = '08';
var value = parseInt(test);

I wan't 08 I currently get it to work like this, but there must be a better way.

if (test.charAt(0) == '0') test= test.charAt(1);
value = parseInt(test);

answer=
There is an optional parameter that allows you to specify base ten. If there are leading zeros for some unknown reason to me parseInt will treat the number as an octal number (base 8) just do it like this:

var test = '08';
var value = parseInt(test,10);

...That one pissed me off forever until I found out what was going on.

Glad to help :)

No comments: