isInt
For example, if a text input field in a form is supposed to contain only integers between 100 and 200, you can use JavaScript to verify that the value is within that range. However, since JavaScript treats text input fields like strings, you first need to convert them to integers, using the parseInt
function. before performing numerical operations on them.
In its simplest form, the parseInt
function requires just one parameter, a string. Beginning with the first character, parseInt
scans the string for digits and determines the integer value that the sequence of digits represents. parseInt
stops scanning the string when it encounters a non-digit character. Here are some examples of how the parseInt
function works:
The last example requires explanation. There is a special value in JavaScript called "NaN," which stands for "Not a Number." When the result of certain numeric operations cannot be determined, the result is often given as NaN. The expression 5 / 0, for example, evaluates to NaN because division by zero is undefined. Since the string "hello" cannot be converted into an integer,
parseInt ("25")
=> 25 parseInt ("101 Dalmatians")
=> 101 parseInt ("hello")
=> NaN
parseInt ("hello")
returns Nan.
After converting a string to an integer, you should verify that the conversion was successful before you use the result. Failure to do so may result in a barrage of "JavaScript error" messages that scare your users away. The JavaScript isNaN
function is available for just this purpose. isNaN
accepts one parameter, the value being tested, and returns the boolean value true
if the parameter is NaN, false
otherwise.
What follows is a generalized function for testing whether or not a string represents an integer. It accepts one parameter, the string being tested, and returns true
if the string represents a valid integer, false
otherwise. You may click on any part of the code to learn what it does.
function isInt (str) { var i = parseInt (str); if (isNaN (i)) return false; i = i . toString (); if (i != str) return false; return true; }