January 15, 2000 - Comparing Numeric Strings | WebReference

January 15, 2000 - Comparing Numeric Strings

Yehuda Shiran January 15, 2000
Comparing Numeric Strings
Tips: January 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

When you accept user's inputs via a form, you end up with string data. More often than not you may want to compare two numeric items. The built-in parseInt() function converts a numeric string to an integer. The following example shows how to use it:

var numStr = "99";
document.write("The initial " + typeof numStr + " is " + numStr);
document.write("<BR>");
var num = parseInt(numStr);
document.write("The converted  " + typeof num + " is " + num);

The script's output is:

The initial string is 99
The converted number is 99

If a non-integer numeric string is given to the function, it returns the nearest integer, as a number.

See more examples for using the parseInt() function in Column 46, A DOM-Based Snakes Game, Part I.