The JavaScript parseFloat() method
The parseFloat() function parses a string and returns a floating-point (decimal) number, reading the leading numeric part. parseFloat("3.14rem") is 3.14. Unlike parseInt(), it keeps the decimal portion and takes no radix. It returns NaN if the string doesn't start with a number.
Overview
parseFloat() is the decimal-aware sibling of parseInt(). It reads a number from the start of a string — including the fractional part — and stops at the first character that can't be part of a number. parseFloat("3.14rem") returns 3.14, perfect for pulling a measurement out of a CSS-style value.
Unlike parseInt(), it takes no radix argument (it's always base 10) and it keeps everything after the decimal point. It also understands scientific notation, so parseFloat("1.5e3") is 1500. If the string doesn't begin with a number, it returns NaN.
As with parseInt(), the choice between parseFloat() and Number() comes down to leniency. parseFloat() grabs the leading number and ignores trailing text; Number("3.14rem") is NaN because the whole string isn't a number. Use parseFloat() to extract a value from mixed text, and Number() when the input should be a clean number.
Syntax
parseFloat(string)
parseFloat("3.14") // 3.14
parseFloat("3.14rem") // 3.14 (stops at 'r')
parseFloat("1.5e3") // 1500
parseFloat("abc") // NaN
Parameters
The parseFloat() method accepts the following parameters.
| Parameter | Description |
|---|---|
string |
The value to parse. Leading whitespace is ignored; parsing stops at the first character that can't be part of the number. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const values = ['12.5kg', '3.14', '1.5e2', 'none'];
const parsed = values.map(v => parseFloat(v));
document.getElementById('out').textContent = parsed.join(', ');
// 12.5, 3.14, 150, NaN
</script>
Best practices
- Use
parseFloat()when the value may have decimals or a trailing unit. - Use parseInt() when you specifically want a whole number.
- Use
Number()when the whole string must be a clean number. - Validate the result with Number.isNaN().
Frequently asked questions
What is the difference between parseFloat() and parseInt()?
parseFloat() keeps the decimal part; parseInt() returns a whole number and takes a radix. Use parseFloat() for decimals.Does parseFloat() take a radix?
What is the difference between parseFloat() and Number()?
parseFloat() reads the leading number and ignores trailing text; Number() requires the entire string to be numeric or returns NaN.How do I extract a decimal from "3.14rem"?
parseFloat("3.14rem"), which returns 3.14.