The parseFloat() Function
The basic syntax of the
parseFloat() function is:
Let’s take an example to understand how the
parseFloat() function works.
// Example 1 let num = parseFloat('10.5'); console.log(num); // Output: 10.5 // Example 2 let num2 = parseFloat('20'); console.log(num2); // Output: 20
In Example 1, the
parseFloat() function converts the string ‘10.5’ into the floating-point number 10.5 and assigns it to the variable
num. The console then logs the value of
num, which outputs 10.5.
In Example 2, the
parseFloat() function converts the string ’20’ into the floating-point number 20 and assigns it to the variable
num2. The console logs the value of
num2, which outputs 20.
The parseFloat() function has a few limitations that are important to keep in mind.
- If the string starts with a non-numeric character or does not contain any numeric characters, the function will return NaN (Not-a-Number).
- The function stops parsing as soon as it encounters an invalid character. For example, if the string is ‘10.5abc’, the function will only convert ‘10.5’ and ignore the rest of the characters.
- The function does not handle exponential notation. If you need to parse numbers in scientific notation, you should use the
Let’s look at some examples to understand these limitations better.
// Example 1 let result1 = parseFloat('abc'); console.log(result1); // Output: NaN // Example 2 let result2 = parseFloat('10.5abc'); console.log(result2); // Output: 10.5 // Example 3 let result3 = parseFloat('1e5'); console.log(result3); // Output: 1
In Example 1, since the string ‘abc’ is not a valid number, the
parseFloat() function returns NaN.
In Example 2, even though the string ‘10.5abc’ contains invalid characters after ‘10.5’, the function successfully converts ‘10.5’ into a number and ignores the rest of the characters.
In Example 3, since
parseFloat() does not handle exponential notation, it stops parsing at ‘1’ and returns that value instead of converting it into scientific notation (1e5 = 100000).
parseFloat() can be a powerful tool for converting string data into the desired numeric format.
By understanding and utilizing the
I hope this article has provided you with a clear understanding of the