Michael Gaigg: Über UI/UX Design

7Oct1

The importance of the JavaScript parseInt radix

Problem:

Just recently I had to implement an HTML form that allows users to enter percentage values. Like every good programmer I added client-side validation to check that the input values are between 0 and 100.

Using the JavaScript function parseInt(txtValue) with txtValue being the value of the input field our tester was able to submit the form with a value of 0137.

My first reaction was to restrict the maxlength attribute of the input field to 3 characters only. Even though this is a good and recommended practise there was clearly something else wrong.

Explanation:

The parseInt() function parses a string and returns an integer. The signature is parseInt(string, radix) with

  • string (required) being the string to be parsed, and
  • radix (optional) a number (from 2 to 36) that represents the numeral system to be used

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)
  • If the string begins with any other value, the radix is 10 (decimal)

Solution:

So, what happened? Because I forgot to specify the radix and our QA tester tried the (however unlikely) case of 0137 JavaScript assumed it was an octal number and returned a value of 95. Lesson learned: Always specify the radix (if it decimal set it to 10 ;) !!!!

PS.: Only the first number in the string is returned!
PPS.: Leading and trailing spaces are allowed.
PPPS.: If the first character cannot be converted to a number, parseInt() returns NaN.

Similar Posts:

Liked this article? Help and share it:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • StumbleUpon
  • Technorati
  • Twitter
  • Yahoo! Buzz

About Michael Gaigg

Michael Gaigg is a User Interface Expert at ESRI. His expertise includes User-centered Design (UCD), Usability, Accessibility and Section 508, Web Development and Web Design.
Comments (1) Trackbacks (0)
  1. I do not suggest to use short maxlength values. Especially not that short as three characters. When editing the value I often input the new letters first and delete the wrong ones after. Or when I want to copy and paste something which does not fit the value in the first place but if contains the value I want to enter but want to delete the rest within the input field.

    The length can be checke when the form is submitted. And it must be checked on the server side in any case.

    PS: I stumbled upon the radix once but I’ve forgotten it since!


Leave a comment


No trackbacks yet.