parseFloat(input_string);
By using parseFloat function we can convert strings to float numbers. To convert string to integer we can use parseInt function. Using this function we can only convert string numbers to numeric data but alphabetic characters we can't convert.
<script>
document.write(parseFloat(2)); // Output 2
document.write("<br>");
document.write(parseFloat(2.4)); // Output 2.4
document.write("<br>");
document.write(parseFloat(-3.9)); // Output -3.9
document.write("<br>");
document.write(parseFloat('2.4')); // Output 2.4
document.write("<br>");
document.write(parseFloat('-2.4')); // Output -2.4
document.write("<br>");
document.write(parseFloat('Hello')); //Output NaN
document.write("<br>");
document.write(parseFloat('5ab')) // Output 5
document.write("<br>");
document.write(parseFloat('ab5')) // Output NaN
document.write("<br>");
document.write(parseFloat(' 50 ')) // Output 50
document.write("<br>");
document.write(parseFloat()); // Output NaN
</script>
Main use of the parseFloat function is to convert user entered data of a text box to number as by default all the data entered through a text box is string.
Let us try to learn parseFloat function by using one example. Try to enter two numbers in two text fields. The sum of the two numbers will be displayed on click of a button.
<script type="text/javascript">
function disp_data(){
document.getElementById("a2").innerHTML=parseFloat(document.getElementById('t1').value) + parseFloat(document.getElementById('t2').value);
}
</script>
<input type=text name=t1 id='t1' > <input type=text name=t2 id='t2' > <input type=button value='Display Sum' onClick='disp_data()';>
<div id='a2' style=" background-color: #c0f0c0; width:200" > Enter a number</div>
<p class='demo'><a href=math-parseFloat.php>Back to Tutorial of Math.parseFloat() function</a></p>
Absolute value of integer