Links

Lists

Latest Updates

Ruby On Rails List
Python list
Advanced Java
The JavaScript List
Apache Users
Full Disclosure
Linux Security

Search the archives!


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Javascript] parseInt glitch


  • From: peter at brunone.com (Peter Brunone)
  • Subject: [Javascript] parseInt glitch
  • Date: Tue Aug 16 20:58:45 2005

Hi Tyson,

	I came across this years ago and it confused the heck out of me.

	The parseInt function is a bit more complex than you realize.
With it, you can parse integers out of any base you like, by specifying
an optional second parameter (I think you can see where this is going).

	Anyway, if you *don't* specify the second parameter, the
function takes a guess based on your format.  If the string starts with
a zero and then an "x", it's assumed to be hexadecimal.  If it starts
with zero and then a number, it's assumed to be octal.  Of course in
that case (base 8), 8 and 9 don't exist... which brings us to this
behavior.

	To make sure you always parse in base 10, call your parseInt
with the appropriate radix:

parseInt('08', 10)

...and you'll get the right answer.

HTH,

Peter

-----Original Message-----
From: javascript-bounces@xxxxxxxxxx On Behalf Of tyson

I'm using javascript to validate the syntax of a "date" input by the 
user.  I split the string variable by "/" and then check each month, 
day, year...  Anyways,  I noticed that when I use the function 
parseInt(month), I get an error if its higher than '07'.  For example:
       parseInt('01') = 1
       parseInt('02') = 2
       parseInt('07') = 7 
 but parseInt('08') = 0
and parseInt('09') = 0

This problem only occurs if there's a "0" in front of the number.   If I

do parseInt('8') it works fine, but parseInt('08') doesn't.  Does 
anybody know why it does this?  I don't want to mask out the "0" if I 
don't have to, but that looks like the only option now.  I tested this 
on a command line, so I know its not just my program.  Any  help would 
be appreciated!

  -Tyson