Converting Strings to Numbers
If you prompt the user for a number, using the prompt function, what you actually get
is a string that contains the "number".
This is also the case, if you look at the value of a text field on a form.
This means that before you can use the number, you must convert it to a "real" number.
parseInt and parseFloat
To convert the string containing the number to a "real" number, you can use
either parseInt or parseFloat functions.
parseInt returns an integer and parseFloat returns a float (i.e has a decimal) number.
Example: i= parseInt(string) or x= parseInt(string)
Allowing JavaScript To Convert For You
JavaScript will convert a string to a number for you automatically, HOWEVER it may not handle it properly, especially if there is a '+' operator involved. Remember the '+' operator adds numbers and cpmcatenates strings.
This script asks you for a number
and shows you the results of various conversions between strings and numbers.
Reload the page and try several different number for integer and real.
Note, the results may vary depending on browse version/platform, etc.
Back