/

The parseFloat() Method in JavaScript

The parseFloat() Method in JavaScript

Introduction

In JavaScript, the parseFloat() method is part of the Number object. It is used to parse a string argument as a floating-point number and return the parsed value. This method is particularly useful when you need to convert a string representation of a number into an actual number.

Syntax

The syntax for using the parseFloat() method is as follows:

1
Number.parseFloat(string)

Examples

Here are some examples demonstrating the usage of the parseFloat() method:

1
2
3
4
5
6
7
8
9
10
Number.parseFloat('10')    // Returns 10
Number.parseFloat('10.00') // Returns 10
Number.parseFloat('237,21') // Returns 237
Number.parseFloat('237.21') // Returns 237.21
Number.parseFloat('12 34 56') // Returns 12
Number.parseFloat(' 36 ') // Returns 36
Number.parseFloat('36 is my age') // Returns 36

Number.parseFloat('-10') // Returns -10
Number.parseFloat('-10.2') // Returns -10.2

As you can see, the parseFloat() method is quite flexible. It can handle different formats of numbers, such as integers, decimals, and negative numbers. It also disregards leading and trailing white spaces in the input string.

Limitations

It’s important to note that the parseFloat() method only handles radix 10 numbers. If the input string contains characters other than digits, decimal points, and sign symbols (+/-), the method will stop parsing and return NaN (Not a Number).

For example:

1
Number.parseFloat('I am Flavio and I am 36') // Returns NaN

Conclusion

The parseFloat() method in JavaScript is a powerful tool for parsing string representations of numbers, especially when dealing with user input or data retrieved from external sources. It allows you to convert strings into floating-point numbers with ease.

tags: [“JavaScript”, “parseFloat()”, “Number object”]