The parseFloat() function is used to accept a string and convert it into a floating-point number. If the input string does not contain a numeral value or If the first character of the string is not a number then it returns NaN i.e, not a number. This function returns a floating-point number parsed up to that point where it encounters a character that is not a number.
Table of Contents
- Syntax & explanation
- Example Output for different inputs
- Other Conditions
- Other Related Concepts
Syntax and explanation
Parameters>: This function accepts a single parameter as mentioned above and described below:
String: This parameter, a mandatory input contains a string that is converted to a floating-point number.
Return value: It returns a floating-point Number and if the first character of a string cannot be converted to a number then the function returns NaN i.e, not a number.
Example Output for different inputs
- If parseFloat encounters a character other than a plus(+), minus (-), numerals (0–9), decimal (.), or exponent (e or E), it returns the value up to that character, ignoring the invalid character and characters following it.
- A second decimal point also stops parsing (characters up to that point will still be parsed).
- Leading and trailing spaces in the argument are ignored.
- If the argument’s first character can’t be converted to a number (it’s not any of the above characters), parseFloat returns NaN.
- parseFloat can also parse and return Infinity.
- parseFloat converts BigInt syntax to Numbers, losing precision. This happens because the trailing n character is discarded.