Function:
parseFloat
parseFloat(string)
The top-level function, parseFloat, finds the first number
in a string.
The function determines if the first character in the string
argument is a number, parses the string from left to right until it
reaches the end of the number, discards any characters that occur after
the end of the number, and finally returns the number as a number (not
as a string).
Only the first number in the string is returned, regardless of how
many other numbers occur in the string.
If the first character in the string is not a number, the function
returns the Not-a-Number value NaN.
Code:
document.write("<BR>" + parseFloat("50"))
document.write("<BR>" + parseFloat("50.12345"))
document.write("<BR>" + parseFloat("32.00000000"))
document.write("<BR>" + parseFloat("71.348 92.218 95.405"))
document.write("<BR>" + parseFloat("37 aardvarks"))
document.write("<BR>" + parseFloat("Awarded the best wine of 1999"))
Output:
50
50.12345
32.00000000
71.348
37
NaN
You can use the isNaN function to
see if the returned value is a NaN.
Code:
cost = "$99.88"
CheckNum = parseFloat(cost)
if(isNaN(CheckNum))
{
document.write("<BR>Sorry, CheckNum is
a NaN")
document.write("<BR>Left-most character
= " + cost.substring(0,1))
}
Output:
Sorry, CheckNum is a NaN
Left-most character = $
|