0
0
JavascriptHow-ToBeginner · 3 min read

How to Parse Float in JavaScript: Simple Guide

To parse a float number in JavaScript, use the parseFloat() function which converts a string to a floating-point number. It reads the string from left to right and stops parsing when it encounters a character that is not part of a valid number.
📐

Syntax

The parseFloat() function takes a single argument, a string, and returns a floating-point number if the string starts with a valid number.

  • parseFloat(string): Converts the string to a float.
  • If the string does not start with a number, it returns NaN (Not a Number).
javascript
parseFloat(string)
💻

Example

This example shows how parseFloat() converts strings to floating-point numbers and stops parsing at the first invalid character.

javascript
console.log(parseFloat('3.14'));       // 3.14
console.log(parseFloat('10.5abc'));    // 10.5
console.log(parseFloat('abc10.5'));    // NaN
console.log(parseFloat('  7.89  '));   // 7.89
console.log(parseFloat('0.123e2'));    // 12.3
Output
3.14 10.5 NaN 7.89 12.3
⚠️

Common Pitfalls

Common mistakes include passing non-string types or expecting parseFloat() to parse the entire string if it contains extra characters after the number.

Also, parseFloat() ignores trailing characters after the number but returns NaN if the string does not start with a number.

javascript
console.log(parseFloat('123abc456'));  // 123 (stops at 'a')
console.log(parseFloat('abc123'));      // NaN (no number at start)

// Wrong way: expecting full string to be a number
const num = parseFloat('12.34.56');
console.log(num); // 12.34 (stops at second dot)
Output
123 NaN 12.34
📊

Quick Reference

UsageDescription
parseFloat('3.14')Returns 3.14 as a number
parseFloat('10.5abc')Returns 10.5, stops parsing at 'a'
parseFloat('abc10.5')Returns NaN, no number at start
parseFloat(' 7.89 ')Trims spaces and returns 7.89
parseFloat('0.123e2')Parses scientific notation, returns 12.3

Key Takeaways

Use parseFloat() to convert strings to floating-point numbers in JavaScript.
parseFloat() reads from the start of the string and stops at the first invalid character.
If the string does not start with a number, parseFloat() returns NaN.
parseFloat() ignores trailing characters after the number but does not validate the entire string.
Always check for NaN to handle invalid inputs safely.