Convert textual decimal input
Read decimal values from user input or text fields that may contain surrounding whitespace.
JavaScript · Function
parseFloat() converts its argument to a string and parses the longest valid decimal-number prefix. It returns the resulting floating-point number, Infinity, or NaN when parsing cannot begin.
parseFloat() first converts its argument to a string, ignores leading whitespace, and reads the longest prefix that forms a decimal number. It returns the resulting floating-point value, including Infinity where applicable, or NaN when no valid number begins the input.
parseFloat(string)| Name | Type | Description |
|---|---|---|
string | any | The value to parse, coerced to a string. Leading whitespace in this argument is ignored. |
A floating point number parsed from the given string, or NaN when the first non-whitespace character cannot be converted to a number.
const inputs = [" -12.5px", "3.14e2", "0x10", "Infinity", "oops"];
for (const input of inputs) {
console.log(input, parseFloat(input));
}The function trims leading whitespace, reads the longest valid decimal prefix, and returns a number or NaN.
Read decimal values from user input or text fields that may contain surrounding whitespace.
Extract a leading numeric measurement from strings such as "12.5px".
Accept decimal scientific notation such as "3.14e2".
parseFloat(string) converts its argument to a string, trims leading whitespace, and parses the longest valid decimal-number prefix. It returns that number, or NaN if the first non-whitespace character cannot begin a valid number.
Follow-up: How does it differ from Number()? Number() requires the whole converted string to represent a valid number, whereas parseFloat() can stop at trailing invalid characters.
It accepts decimal digits, one decimal point, an optional exponent, an optional leading sign, and the Infinity literal. A sign after an exponent marker is also permitted.
Follow-up: What happens with hexadecimal notation? A string beginning with 0x does not use parseFloat()'s decimal syntax, so it does not produce a hexadecimal value.
parseFloat() does not preserve BigInt precision. A BigInt is converted to a string and parsed as a floating-point number, while a string ending in n is parsed only up to the n character.
Follow-up: Why can precision be lost? JavaScript floating-point numbers cannot represent every integer exactly, so large integer values may be rounded during conversion.
Number.parseFloat()parseInt()Number()Number.isNaN()