Javascript parseInt() quirk

I ran into a little quirk or ‘bug’ today when using parseInt() with a string (input from a text box). Now as we all know parseInt() parses a string and returns an integer value.

The scenario: I was working on a legacy application where a user could pass a date to the server in 3 separate form fields (day, month and year); all text boxes. No nice little DHTML calendars here :(

Anyways, the validation on the month text box was being tripped when a user entered a value like ’08′ or ’09′ for the month, note the leading 0.

The parseInt() function can take 2 arguments – the first is the string to be parsed and the second is a radix. The radix parameter is used to specify which numeral system to be used but if it is not supplied (as it most commonly is not), the function tries to determine what to use based on the submitted string. If the string passed to parseInt() begins with a ’0′, then it is parsed in octal ( base 8 ). Note that this ‘bug’ does not happen with parseFloat().

Keep in mind that this only happens when the value being checked is a string and only when the string starts with a leading zero. So that’s why it is difficult to notice. But if you’re dealing with a web page that has user input, there’s nothing prevening the user from entering ’08′ for a number field. To be 100% confident that you won’t see the bug, use one of these two techniques:

parseInt(parseFloat())

parseInt(, 10)

The first example uses parseFloat() which doesn’t suffer from this little quirk and the second used the radix value of 10.

Muchas gracias to Pradeep for the tip :)

Post a Comment or Leave a Trackback

3 Comments

  1. Sean
    September 26, 2007 at 5:53 pm | Permalink

    Thanks for this. I spent half the day trouble shooting this very issue.

  2. JS
    August 13, 2010 at 11:36 am | Permalink

    Hi,
    I noticed this quirk too! Say if your date field is “01/07/2010″ you get “07″ for your month field which needs converting to int 7. If you do (“07″*1) you will get a value 7. JavaScript sees the * sign as an integer function so converts the string to an integer for you.

    What I noticed:
    “07″+1 == “071″ // you can’t do this as it converts to string ‘+’ is overloaded
    “07″*1 == 7 // ok
    “07″-1 == 6 // ok

    Is this better/faster than your method?

  3. Carl Sharman
    September 16, 2010 at 11:50 am | Permalink

    Nice one, just ran into the same issue, thanks for sharing this. Go Sharmans :)

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*