JavaScript parseFloat function

In this blog, let us understand the syntax, usage, and examples of the JavaScript parseFloat() function.

The parseFloat() function is used to accept a string and convert it into a floating-point number. If the input string does not contain a numeral value or If the first character of the string is not a number then it returns NaN i.e, not a number. This function returns a floating-point number parsed up to that point where it encounters a character that is not a number.

Table of Contents

  • Syntax & explanation
  • Example Output for different inputs
  • Other Conditions
  • Application
  • Other Related Concepts

Syntax and explanation

parseFloat(string)

Parameters>: This function accepts a single parameter as mentioned above and described below:

String: This parameter, a mandatory input contains a string that is converted to a floating-point number.
Return value: It returns a floating-point Number and if the first character of a string cannot be converted to a number then the function returns NaN i.e, >not a number.


Example Output for different inputs

function myFunction() {
    parseFloat("9")
    Output: 9
    parseFloat("11.00")
    Output: 9
    parseFloat("10.89")
    Output: 10.89
    parseFloat("10 20 30")
    Output: 10
    parseFloat("   100  ")
    Output: 100
    parseFloat("1 xyz")
    Output: 1
    parseFloat("xyz 1")
    Output: NaN
}

Other Conditions

  • If parseFloat encounters a character other than a plus(+), minus (-), numerals (0–9), decimal (.), or exponent (e or E), it returns the value up to that character, ignoring the invalid character and characters following it.
  • A second decimal point also stops parsing (characters up to that point will still be parsed).
  • Leading and trailing spaces in the argument are ignored.
  • If the argument’s first character can’t be converted to a number (it’s not any of the above characters), parseFloat returns NaN.
  • parseFloat can also parse and return Infinity.
  • parseFloat converts BigInt syntax to Numbers, losing precision. This happens because the trailing n character is discarded.

Applications

parseFloat() function is useful for calculations involving the need to extract numbers from a chunk of text. Although, the text must be broken down into smaller chunks so that the numbers are encountered at the beginning of the sentence. This is one of the biggest disadvantages of this function. Also, parseFloat() works only with base 10 or decimal numbers. It fails to work with hexadecimal and octal number systems.