parseFloat() global function JS Home  <<  JS Reference  <<  parseFloat()

Global function that converts a string to a float.

Description

Parses a string argument (converting it to a string first if required) and attempts to return a floating point number.

Syntax

Signature Description
parseFloat(string)Global function that converts a string to a float.

Parameters

Parameter Description
stringThe string value you want to parse.
  • Leading and trailing spaces are allowed and will be ignored.
  • If the first non space character is not a sign (+ or -), numeral (0-9), decimal point or an exponent, and cannot be converted to a number, parseFloat returns NaN.
  • While parsing after the first non space character if the function encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all subsequent characters.

Examples


Below are some examples of using the parseFloat() function.


// Parsing string to floats.
var parsedValues = new Array(6);

parsedValues[0] = parseFloat('17'); // integer
parsedValues[1] = parseFloat('17.2345'); // valid 
parsedValues[2] = parseFloat('-17.2345'); // negative 
parsedValues[3] = parseFloat('  17.2345   '); // within spaces
parsedValues[4] = parseFloat('17.2345ignored'); // ignore non decimal suffix
parsedValues[5] = parseFloat('abcdef'); // invalid

alert(parsedValues);

Press the button below to action the above code:

Related Tutorials

JavaScript Intermediate Tutorials - Lesson 6 - More Maths Functions