JavaScript parseFloat() method | convert string to float number

JavaScript parseFloat() used to convert a string into a floating-point number. The parseFloat() is an inbuilt function in JavaScript, which parses a string and returns a floating-point number.

Syntax

Parameter Values

String Value converted to a floating point number.

Return value

It returns a floating-point Number or if can’t be converted then the function returns NaN i.e, not a number.

Examples of JavaScript parseFloat() method

Let’s see the different example of how to convert string to float number.

Parse Number strings

Simple basic example

Output:

JavaScript parseFloat method

Different type of string and result

Output

convert string to float number

Dealing with float precision in Javascript

Working on a function in JavaScript and take two variables x and y.

Needed to divide two variables and display result on the screen:

Getting the result as :

But want that result was shown as:

Solution

Try this it is rounding to 3 numbers after coma:

Now your result will be a string. If you need it to be float just do:

Complete example

How to JavaScript parseFloat comma

Answer: You have to first remove the commas using replace method.

Read more: JavaScript replace all Word | space, comma | special characters

Output JavaScript parseFloat empty string

Output JavaScript parseFloat empty string

Note:

  • Leading and trailing spaces are allowed.
  • Only the first number in the string is returned.
  • If the first character can’t be converted to a number, parseFloat() returns NaN.

Do comment if you have any doubts and suggestions on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.