October 2006 Technical Tip JavaScript: parseInt with radix

If you use JavaScript to validate user entries on an HTML form, then you need to be aware of the radix option on the parseInt method. Here's the problem: the default behavior of the parseInt method is to treat a number with leading zeroes as octal, or base 8! For example, if a user types "021" in a text field and submits a form, the parseInt method in its "typical" form will return 17 rather than 21:

0218 = 2*81 + 1*80 = 16 + 1 = 1710

So how do you fix this? It's very simple. There is an overloaded parseInt which accepts the radix, or base. So in general, you should replace this: var myInt = parseInt(myEntry) with var myInt = parseInt(myEntry,10)

Here are the screenshots from a JavaScript program which illustrates the use of radix. Note that you can specify a radix other than 10, for example, 16 as shown here:

Download source here.

We hope you will consider Caliber Data Training when you are in need of high quality JavaScript training.

Go to the articles index. Written by Bill Qualls. Copyright © 2006 by Caliber Data Training 800.938.1222