The JavaScript parseFloat() method is used to parse a string and convert it into a floating-point number. It reads from the start of the string and stops when it encounters a character that is not part of a valid number.
Syntax:
parseFloat(string)
Parameters:
string: The value to parse. This is usually a string, but other types are also allowed (they will be coerced to a string).
Return Value:
A floating-point number if the string contains a valid number.
NaN (Not-a-Number) if the first character cannot be converted into a valid number.
Behavior:
1. Parses the string until it encounters an invalid character.
2. Ignores leading and trailing whitespaces.
3. Recognizes scientific notation (e.g., “1.23e+2”).
4. Does not throw errors for invalid input; instead, it returns NaN.
Examples:
Valid conversions:
parseFloat(“10.5”); // 10.5
parseFloat(“3.14 is pi”); // 3.14 (stops at the first invalid character)
parseFloat(” -0.567 “); // -0.567 (ignores leading/trailing spaces)
parseFloat(“1.2e3”); // 1200 (scientific notation)
Invalid conversions:
parseFloat(“abc”); // NaN (cannot convert)
parseFloat(“”); // NaN (empty string)
parseFloat(” “); // NaN (only whitespace)
Notes:
Use isNaN() to check if the result of parseFloat() is NaN.
If you need to ensure the entire string is a valid number, consider additional validation.
parseFloat() does not handle commas or currency symbols; use libraries like Number() or Intl.NumberFormat for complex parsing.