The parseFloat()
function parses a string and returns a floating point number.
parseFloat() uses the following rules to convert string to float point value.
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.
parseFloat |
Yes | Yes | Yes | Yes | Yes |
var v = parseFloat(string)
Parameter | Description |
---|---|
string | Required. The string to be parsed |
A Number type value. If the first character cannot be converted to a number, NaN is returned.
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: