parseFloat() converts the beginning of a string to a JavaScript Number and supports decimal points and exponent notation. If parsing cannot begin with a valid number, it returns NaN.
console.log(parseFloat("12.75px")); // 12.75
console.log(parseFloat("px12.75")); // NaN
parseFloat(string)
Number.parseFloat(string)Number.parseFloat() has the same parsing behavior as the global parseFloat().
console.log(parseFloat(2)); // 2
console.log(parseFloat(2.4)); // 2.4
console.log(parseFloat(-3.9)); // -3.9
console.log(parseFloat("2.4")); // 2.4
console.log(parseFloat("-2.4")); // -2.4
console.log(parseFloat("Hello")); // NaN
After parsing has started, parseFloat() ignores trailing characters it cannot use. This is useful for known unit suffixes, but it can also accept malformed input that Number() would reject.
console.log(parseFloat("5.25kg")); // 5.25
console.log(parseFloat("kg5.25")); // NaN
console.log(parseFloat(" 50.5 ")); // 50.5
console.log(parseFloat("+8.2")); // 8.2
console.log(parseFloat()); // NaN
console.log(parseFloat("1.5e3")); // 1500
console.log(parseFloat("Infinity")); // Infinity
console.log(parseFloat("12.5px")); // 12.5
console.log(Number("12.5px")); // NaNUse Number() when the entire string must represent one number. Use parseFloat() when intentionally parsing a numeric prefix.
parseInt() parses an integer prefix and supports a radix. parseFloat() retains the decimal fraction and does not accept a radix argument.
console.log(parseFloat("19.95")); // 19.95
console.log(parseInt("19.95", 10)); // 19
const value = parseFloat("abc");
if (Number.isNaN(value)) {
console.log("No decimal number was found");
}Read more about NaN and numeric checks.
Form controls provide strings. Parse each field before adding; otherwise the + operator may concatenate strings.
const first = parseFloat(document.getElementById("t1").value);
const second = parseFloat(document.getElementById("t2").value);
const sum = first + second;
document.getElementById("result").textContent = sum;
Compare parseInt(), Math.abs(), and number validation.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.