parseFloat()
parseFloat(
value,defaultValue):number
Parses a string to a float, returning default if invalid.
note
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"