Wednesday, April 18, 2007

Javascript and Java parseInt

Make sure to specify the radix (base) when using parseInt to convert from string to numerical values. Otherwise if your number is prefixed with zero, a non decimal base is assumed!

In Java:
n = Integer.parseInt(s,10);

In Javascript:
n = parseInt(s,10);

From w3Scholls.com Javascript reference website:

If the radix parameter is omitted, JavaScript assumes the following:

  • If the string begins with "0x", the radix is 16 (hexadecimal)
  • If the string begins with "0", the radix is 8 (octal). This feature is deprecated
  • If the string begins with any other value, the radix is 10 (decimal)
So, you can see how important it is to specify the radix in the case where you are parsing date strings like 08-08-2007. Without specifying the radix, you'd end up with Oct 10, 2007!

No comments: