HTML and CSS Reference
In-Depth Information
To convert a text string to a number, you can apply an arithmetic operator (other than the
+ operator) to the text string. The following code takes the text string
123
and multiplies it
by 1. The end result is that JavaScript converts the text string
123
to the numeric value 123.
testString = “123”; // text string
testNumber = testString*1; // numeric value
Another way of converting a text string to a numeric value is to use the
parseInt()
function, which extracts the leading integer value from a text string. The syntax of the
parseInt()
function is
parseInt(
text
)
where
text
is the text string or variable from which you want to extract the leading
integer value. The
parseInt()
function determines whether the first nonblank character
in the text string is a number. If it is, the function then parses the text string from left to
right until the end of the number or a decimal point is encountered. Any characters in
the string after that are discarded. The
parseInt()
function returns only the first integer
in the string; it does not return decimal points or numbers to the right of a decimal. If a
text string does not begin with a number, the
parseInt()
function returns the value
NaN
,
indicating that the text string contains no accessible number. The following are some
sample values returned by the
parseInt()
function:
parseInt(“120 lbs”); // returns 120
parseInt(“206.58 lbs”); // returns 206
parseInt(“weight equals 55 lbs”); // returns NaN
You also can use the
parseFloat()
function to extract numeric values other than inte-
gers from text strings. The
parseFloat()
function has the syntax
parseFloat(
text
)
where
text
is a text string or a variable containing a text string. The
parseFloat()
function works like the
parseInt()
function except that it retrieves both integers and
numbers with decimals. The following are sample values returned by the
parseFloat()
function:
parseFloat(“120 lbs”); // returns 120
parseFloat(“206.58 lbs”); // returns 206.58
parseFloat(“weight equals 55 lbs”); // returns NaN
Finally, you can use the JavaScript
eval()
function to evaluate numeric expressions
entered as text strings. For example, the statement
eval(“3 + 2*5”)
returns the numeric value 13. One application of the
eval()
function is to evaluate text
strings stored in text input boxes on Web forms and return their numeric values. The
eval()
function has uses in JavaScript in addition to evaluating numeric expressions, but
they are beyond the scope of this tutorial.
Figure 11-28 summarizes the different JavaScript methods and functions used to work
with numeric values.