To convert a string to a float in JavaScript, use the parseFloat() function. It parses a string and returns a floating-point number, ignoring leading whitespace and stopping at the first invalid character.
Basic usage:
parseFloat("123.45")returns123.45.Handles non-numeric prefixes:
parseFloat("abc123.45")returns123.45.Returns
NaNif the first non-whitespace character cannot be converted:parseFloat("abc")returnsNaN.Supports scientific notation:
parseFloat("1.23e4")returns12300.Trims whitespace:
parseFloat(" 45.67 ")returns45.67.
For strings using commas as decimal separators (e.g., French format), replace commas with dots first:parseFloat("123,45".replace(",", ".")) returns 123.45.
Alternatively, use the unary plus operator (+) for a concise conversion:+ "123.45" returns 123.45.
Note:
parseFloat()is more lenient thanNumber()— it ignores trailing invalid characters, whileNumber()returnsNaNif the entire string isn’t a valid number.
If they're meant to be separate values, try this:
var values = "554,20".split(",")
var v1 = parseFloat(values[0])
var v2 = parseFloat(values[1])
If they're meant to be a single value (like in French, where one-half is written 0,5)
var value = parseFloat("554,20".replace(",", "."));
Answer from Jesse Rusak on Stack OverflowConverting a string to a float in Javascript?
Convert string to Float
What is the fastest way to convert string to float out of these 13 methods?
Library/function that will tidy up weird JS float values without converting to string in between?
Videos
If they're meant to be separate values, try this:
var values = "554,20".split(",")
var v1 = parseFloat(values[0])
var v2 = parseFloat(values[1])
If they're meant to be a single value (like in French, where one-half is written 0,5)
var value = parseFloat("554,20".replace(",", "."));
Have you ever tried to do this? :p
var str = '3.8';ie
alert( +(str) + 0.2 );
+(string) will cast string into float.
Handy!
So in order to solve your problem, you can do something like this:
var floatValue = +(str.replace(/,/,'.'));
I can't use parseFloat(). I am so far doing the obvious by checking each character, but I feel there has to be a more elegant way! My function needs to act exactly the same as parseFloat() does. Can anyone help?