JavaScript Reference ยท Global Functions and Values
The parseFloat() function
Reference for JavaScript parseFloat(): converting strings to decimal numbers, partial parsing, exponents, Infinity, NaN results and comparison with Number().
parseFloat() reads a decimal number from the start of a string and returns it as a number. Like parseInt(), it ignores leading whitespace and stops at the first character that does not belong to a number, so "3.5em" becomes 3.5.
It always works in base 10. If the text does not start with a number, the result is NaN.
parseFloat("3.14abc"); // 3.14 parseFloat("1e3"); // 1000
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
parseFloat(string)
| Name | Description |
|---|---|
string |
The value to parse. Non-strings are converted to strings first. Leading whitespace is skipped. |
Return value: a number, or NaN if no number can be read at the start of the string.
Exceptions: none for ordinary values.
Usage notes
- Accepted syntax: an optional sign, digits with at most one decimal point, and an optional exponent (
eorEfollowed by an optional sign and digits). The literalInfinity(with a sign) is also recognized. - Only the longest valid prefix is used.
"1.2.3"gives1.2, and"1,5"gives1, because a comma is not a decimal separator in JavaScript. - No hex, binary or octal.
parseFloat("0x10")is0; useparseInt()with a radix orNumber()for those. - Empty and blank strings give
NaN, whereasNumber("")gives0. That difference can matter when validating form fields. - Binary floating point still applies.
parseFloat("0.1") + parseFloat("0.2")is0.30000000000000004. For money, store integer cents or use a decimal library. - Use
Number()for strict parsing. It rejects trailing text, soNumber("12.5kg")isNaN, which is usually what you want for validation. - Locale-formatted text such as
"1.234,56"is not understood. Strip separators yourself or useIntl.NumberFormatfor output. - It is the same function as
Number.parseFloat.
Browser support
parseFloat() works in every browser and JavaScript runtime.
Related
parseInt(),isNaN(),Number(),Number.parseFloat()- Lessons: Type conversion, Numbers