ParseInt(“08”) or “Why I hate JavaScript”

31 05 2011

Let’s do a little exercise. Let’s parse some numbers using JS.

ParseInt(“01”)
1

ParseInt(“02”)
2

ParseInt(“03”)
3

ParseInt(“04”)
4

ParseInt(“05”)
5

ParseInt(“06”)
6

ParseInt(“07”)
7

ParseInt(“08”)
0 (What?)

ParseInt(“09”)
0 (Wait, what!?!)

ParseInt(“10”)
10

Since Javascript uses Octal to parse numbers and starts at zero, 08 and 09 does not exist. They are therefore converted to zero. I found this out the hard way and spent a few hours pulling my own hair in frustration. My logic seemed squeaky clean and I didn’t suspect the parsing had given up on me.

The fix to this is to write:

ParseInt(“08”, 10)
8

Happy coding!

 

1257570397874

Advertisements

Actions

Information

5 responses

1 06 2011
Jesper

Intressant!

MS har dock bestämt sig för att som vanligt inte följa standarden. IE9 använder basen 10 om inget annat anges. >:(

//Jesper

1 06 2011
Viktor Larsson

Gud, det hade varit en mardröm ifall min kund hade fått en resultat i sin browser och jag ett resultat i min browser. Debug-nightmare

1 06 2011
Alex

Actually… From MDC docs an exact behavior description of when radix is not specified or 0….

If radix is undefined or 0, JavaScript assumes the following:

* If the input string begins with “0x” or “0X”, radix is 16 (hexadecimal).
* If the input string begins with “0”, radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.
* If the input string begins with any other value, the radix is 10 (decimal).

More info at: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

Very good last comment:
Although it is optional, most implementations interpret a numeric string beginning with a leading ‘0’ as octal. The following may have an octal result.

1 06 2011
Viktor Larsson

Good to have clarification. Thank you. Doesn’t make me hate it any less though ;)

5 04 2012
Quora

Is it better to learn Python or JavaScript as a first language?…

I actually mostly use Ruby and both love it and hate it at times. So the question is what is best for a beginner as a first language–and here I would argue the best thing o learn is something as close as possible to the original Unix commands. In the …

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: