In JavaScript, the parseFloat() function is used to parse a string and convert it into a floating-point number (a number with decimal points). It takes a single argument, the string to be parsed.
Syntax: parseFloat(string)
- string: The string to be parsed into a floating-point number.
Examples:
1. Basic Usage:
let str = "3.14"; let num = parseFloat(str); console.log(num); // Output: 3.14
2. Parsing Non-Float Strings:
let str = "42"; let num = parseFloat(str); console.log(num); // Output: 42
3. Parsing Strings with Leading and Trailing Whitespaces:
let str = " 3.14 "; let num = parseFloat(str); console.log(num); // Output: 3.14
4. Parsing Strings with Invalid Characters:
let str = "3.14 is a pi approximation"; let num = parseFloat(str); console.log(num); // Output: 3.14
Explanation:
- The parseFloat() function parses a string from left to right until it encounters a character that cannot be part of a floating-point number (e.g., letters or symbols). It then returns the parsed floating-point number.
- Leading and trailing whitespaces are ignored while parsing the string.
- If the string cannot be converted into a valid floating-point number, parseFloat() returns 'NaN' (Not-a-Number).
Use Cases:
- Parsing User Input: Convert user-entered strings into floating-point numbers for mathematical operations or validation.
- Extracting Numbers from Strings: Extract numerical values embedded within strings, even if they are surrounded by other characters.
- Parsing Data from External Sources: Parse numeric data received from APIs or other external sources in string format into floating-point numbers for processing.
The parseFloat() function is a handy tool for converting strings to floating-point numbers in JavaScript, allowing for easy manipulation and computation of numerical data.
Code Compiler Link: https://app.singhteekam.in/codecompiler/