How to convert a string to a floating point number in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

Javascript has provided a method called parseFloat() to convert a string into a floating point number. Floating numbers are nothing but decimals. We also have another method called parseInt() to do the same task but it will not deal with decimals. It returns only integers.

ParseFloat() can change a number string into a number whereas if any string other than a number is sent then it gives NaN as output.

syntax

parseFloat(Value);

It takes a number string as input and returns a floating point number as output.

Example

In the following example, parseFloat() has given floating number as output, whereas parseInt() has given an integer as output.

Live Demo

<html>
<body>
   <script>
      var a = parseFloat(" 100 ");
      document.write(a +"</br>");
      var b = parseFloat("120.65")
      document.write(b +"</br>");
      var c = parseInt("3.14");
      document.write(c +"</br>");
   </script>
</body>
</html>

Output

100
120.65
3

In some cases there are both a number and also a string in a variable then, if the number is at first place then only the number will be returned as output, splicing out the string part, else NaN will be returned as output.

Example

Live Demo

<html>
<body>
   <script>
      var a = parseFloat("  hello ")
      document.write(a +"<br>");
      var b = parseFloat("hello1234")
      document.write(b +"<br>");
      var c = parseFloat("3.14hello");
      document.write(c +"<br>");
   </script>
</body>
</html>

Output

NaN
NaN
3.14
raja
Published on 08-Jul-2019 15:15:22
Advertisements