Javascript Reference - JavaScript parseFloat() Function








The parseFloat() function parses a string and returns a floating point number.

parseFloat() uses the following rules to convert string to float point value.

  • parseFloat() function looks at each character starting in position 0.
  • It continues to parse the string until it reaches either the end of the string or a character that is invalid in a floating-point number.
  • A decimal point is valid the first time it appears, but a second decimal point is invalid and the rest of the string is ignored, resulting in "12.34.5" being converted to 12.34.
  • parseFloat() always ignores initial zeros.
  • It will recognize floating-point with e-notation.
  • Hexadecimal numbers always become 0.
  • Because parseFloat() parses only decimal values, there is no radix mode.
  • If the string represents a whole number (2 or 2.0), parseFloat() returns an integer.

var num1 = parseFloat("1234blue");    //1234 - integer
console.log(num1);/*from  w w  w . j  a v a2s  .  c  o  m*/
var num2 = parseFloat("0xA");         //0
console.log(num2);
var num3 = parseFloat("22.5");        //22.5
console.log(num3);
var num4 = parseFloat("22.34.5");     //22.34
console.log(num4);
var num5 = parseFloat("0908.5");      //908.5
console.log(num5);
var num6 = parseFloat("3.125e7");     //31250000
console.log(num6);

The code above generates the following result.





Browser Support

parseFloat Yes Yes Yes Yes Yes

Syntax

var v = parseFloat(string)

Parameter Values

Parameter Description
string Required. The string to be parsed

Return Value

A Number type value. If the first character cannot be converted to a number, NaN is returned.





Example

The following code shows how to Parse different strings.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--from w  w  w  .  jav  a  2 s  . co  m-->
    var a = parseFloat("1") + "<br>";
    var b = parseFloat("1.00") + "<br>";
    var c = parseFloat("1.33") + "<br>";
    var d = parseFloat("3 45 66") + "<br>";
    var e = parseFloat(" 6 ") + "<br>";
    var f = parseFloat("4 years") + "<br>";
    var g = parseFloat("was 0") + "<br>";

    var n = a + b + c + d + e + f + g;
    document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html>

The code above is rendered as follows: