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.
The parseFloat()
method in JavaScript which parse data / string passed as an argument and return a floating point number.
Syntax:
parseFloat(string)
Here, we have some examples on how e can convert a string of numbers, strings or alphanumeric values into a floating point value.
Examples:
parseFloat(" 20 ")
parseFloat("12345abc")
parseFloat("abc45678")
parseFloat("3.1415")
parseFloat("20 1 1999"
Output:
20
12345
NaN
3.1415
20
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()
encounter a value other then + , - , 0-9, decimal point (.), exponent(e or E), it will ignore the invalid characters.parseFloat()
. Any character up-to that is parse.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