Convert String To Float in JavaScript

Convert String To Float in JavaScript

In this article we will learn how to convert a string to float in JavaScript.

While working with JavaScript we come across some instances where we have to convert a string into a floating value.

Now, in JavaScript we have in-built function parseFloat() which will convert a string into a floating value number.

What is parseFloat()?

The parseFloat() method in JavaScript which parse data / string passed as an argument and return a floating point number.



Example Convert String into Floating value

Here, we have some examples on how e can convert a string of numbers, strings or alphanumeric values into a floating point value.


parseFloat("  20  ")
parseFloat("20 1 1999"



As you can see all the strings are parse as float value using parseFloat(). However to understand why some values are return as NaN (Not A Number ) and only the first digit, you have to see the description below.

parseFloat() arguments and return value descriptions

  1. If parseFloat() encounter a value other then + , - , 0-9, decimal point (.), exponent(e or E), it will ignore the invalid characters.
  2. Second decimal points are not parse by parseFloat(). Any character up-to that is parse.
  3. Leading and trailing spaces are ignored.
  4. If the first character is not a number then it will return NaN (Not A Number)
  5. It can parse infinity.
  6. parseFloat()converts BigInt values to Numbers .

Related Topics:

How To Repeat A String N Number Of Times In JavaScript

How To Remove Last Character From A String In Javascript

3 Ways To Generate Random String/Characters In JavaScript

How to compare two strings in JavaScript?