parseFloat() Function in JavaScript: Convert String to Number - JavaScript Tutorial
The parseFloat() function is a built-in JavaScript function that converts a string representation of a number into a floating-point number. It parses a string and returns a floating-point number.
Syntax:
parseFloat(string)
Parameters:
- string: The string to be parsed.
Return Value:
The parseFloat() function returns a floating-point number if the string is successfully parsed. If the string cannot be parsed as a number, it returns NaN (Not a Number).
Example:
const string1 = "123.45";
const string2 = "100";
const string3 = "abc";
const number1 = parseFloat(string1); // number1 = 123.45
const number2 = parseFloat(string2); // number2 = 100
const number3 = parseFloat(string3); // number3 = NaN
Notes:
- The parseFloat() function only parses the first part of the string that can be converted to a number. If the string contains non-numeric characters after the first numeric part, they are ignored.
- If the string starts with a non-numeric character, parseFloat() returns NaN.
- If the string is empty, parseFloat() returns NaN.
原文地址: https://www.cveoy.top/t/topic/qfYC 著作权归作者所有。请勿转载和采集!