JavaScriptNumbers and Math
Number. parseFloat()
Converts the start of a string into a floating-point number.
- Returns
- A number, or
NaN.
Example
#JavaScript
console.log(Number.parseFloat('1.5rem'))
console.log(Number.parseFloat('3,5'))
console.log(Number.parseFloat('3,5'.replace(',', '.')))
console.log(Number.parseFloat('.75'))Console
1.5
3
3.5
0.75
Definition and usage
#The Number.parseFloat() function reads a string from the left and converts it into a number with a fractional part. The decimal separator must be a period. Reading stops at the first invalid character.
It’s useful for reading values with units, such as "1.5rem" or "12.5%", when you only care about the number itself.
Numbers written with a comma as the decimal separator, like "3,5", get cut off at the comma, giving 3. Convert the comma to a period before parsing.
Syntax
#Syntax
Number.parseFloat(string)Parameters
#string
string
The text to process.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Convert numbers typed with a comma before parsing:
value.replace(",", "."). - Always check the result with
Number.isNaN()before using it in calculations.
Related entries
#Spotted a mistake or missing an example? Write to us.