JavaScript | parseFloat() with Examples

The parseFloat() is an inbuilt function in JavaScript which is used to accept the string and convert it into a floating point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number. It actually returns a floating point number parsed up to that point where it encounters a character which is not a Number.


Parameters: It accepts a parameter “value” which contains a string which is converted to a floating point number.
Return value: It returns a floating point Number and if the first character of a string cannot be converted to a number then the function returns NaN i.e, not a number.

Input: var n = parseFloat("  2018  ");
Output: n=2018 (floating point Number)
The parseFloat() function ignores leading and trailing spaces and
returns the floating point Number of the string.

Input: var a = parseFloat("1000.04");
Output: now a = 1000.04(floating point Number)

JavaScript codes to show the working of this function:

Code #1:

<!DOCTYPE html>
      // It ignores leading and trailing spaces.
      a = parseFloat("  100  ")
      document.write('parseFloat("  100  ") = ' +a +"<br>");
      // It returns floating point Number until
      // it encounters Not a Number character
      b = parseFloat("[email protected]")
      document.write('parseFloat("[email protected]") = '+b +"<br>");
      // It returns NaN on Non numeral character
      c = parseFloat("[email protected]")
      document.write('parseFloat("[email protected]") = ' +c +"<br>");
      d = parseFloat("3.14")
      document.write('parseFloat("3.14") = '+d +"<br>");
      // It returns only first Number it encounters
      e = parseFloat("22 7 2018")
      document.write('parseFloat("22 7 2018") = ' +e +"<br>");


parseFloat(" 100 ") = 100
parseFloat("[email protected]") = 2018
parseFloat("[email protected]") = NaN
parseFloat("3.14") = 3.14
parseFloat("22 7 2018") = 22

Code #2:
Using isNaN() function to test that converted values are valid number or not.

<!DOCTYPE html>
      var x = parseFloat("3.14");
      if (isNaN(x))
          document.write("x is not a number" + "<br>");
          document.write("x is a number" + "<br>");
      var y = parseFloat("geeksforgeeks");
      if (isNaN(y))
          document.write("y is not a number" + "<br>");
          document.write("y is a number" + "<br>");
     // Difference between parseInt() and parseFloat()
     var v1 = parseInt("3.14");
     var v2 = parseFloat("3.14");
     document.write('Using parseInt("3.14") = ' + v1 + "<br>");
     document.write('Using parseFloat("3.14") = ' + v2 + "<br>");


x is a number
y is not a number
Using parseInt("3.14") = 3
Using parseFloat("3.14") = 3.14

This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment



load comments

Subscribe to Our Newsletter