Don't Use parseInt

Well obviously you should use it if you are using it for its intended purpose of converting between number bases, but that's the only thing you should use it for.

num = parseInt('fe',16); // sets num to 254

The most common misuse of parseInt is for converting a string into a number. Do not use parseInt to convert a string to a number. The Number() function is specifically intended for that purpose. There are even shorter ways to do the conversion for example using a unary plus.

num1 = Number(str1);
num2 = (+str2);

Another misuse of parseInt is for extracting the numeric portion of a CSS property. Now this used to be useful back when all dimensions were entered in pixels but now very few ought to be entered that way. A properly defined stylesheet for the screen will contain a mix of '%' and 'em' and one for printing will contain a mix of 'pt' and either 'in' or 'cm'. So we will normally need that part of the property as well even though we need to separate it in order to apply calculations to the numeric part. Using parseInt therefore only gets us one of the two pieces of information we need to split out of the property. Instead of using parseInt to get half of what we need we can use a simple regular expression to get both at the same time.

dim = /^(\d+)(\D*)$/.exec(cssprop);

This call returns the numeric portion as (+dim[1]) and the rest as dim[2] so that both are available to use in the subsequent processing.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow