parseFloat()
parseFloat(
value,defaultValue):number
Parses a string to a float, returning default if invalid.
remarque
Returns default for NaN, Infinity, and invalid strings. Assumes non-nullish input.
Parameters
value: string
The string value to parse.
defaultValue: number
The value to return if parsing fails.
Returns: number
The parsed float or default value.
See Also
Since
2.0.0
Example
parseFloat('42.99', 0); // => 42.99
parseFloat('invalid', 0); // => 0
parseFloat('Infinity', 0); // => 0
parseFloat('NaN', 100); // => 100
How it works?
Parses a string to a float, returning default if invalid.
Validation Flow
Common Inputs
| Value | Default | Result |
|---|---|---|
'42.99' | 0 | 42.99 |
'invalid' | 0 | 0 |
'Infinity' | 0 | 0 |
'NaN' | 100 | 100 |
'3.14abc' | 0 | 3.14 |
Use Cases
Parse floating-point numbers 📌
Convert a string to a float, with a required default value for failures. Essential for reading configuration values or user input strings.
const taxRate = parseFloat(env.TAX_RATE, 0.2);
Safeguard against NaN
Ensure a calculation never propagates NaN from bad input.
Critical for financial or scientific calculations.
const validValue = parseFloat(userInput, 0); // Returns 0 if input is "abc"