Example 1 — Read a Decimal Number from Text
See which texts parseFloat() understands and where it stops.
console.log("3.14 -> " + parseFloat("3.14"));
console.log("3.14abc -> " + parseFloat("3.14abc"));
console.log(" 2.5kg -> " + parseFloat(" 2.5kg"));
console.log(".5 -> " + parseFloat(".5"));
console.log("-0.75 -> " + parseFloat("-0.75"));
console.log("1e3 -> " + parseFloat("1e3"));
console.log("1.2.3 -> " + parseFloat("1.2.3"));
console.log("abc -> " + parseFloat("abc")); How It Works
- Decimals are kept.
"3.14"gives3.14, and a number that starts with a dot,".5", gives0.5. - Extra text is ignored.
"3.14abc"and" 2.5kg"work, because reading stops at the first letter and spaces at the start are skipped. - Exponents work.
"1e3"means 1 times 10 to the power 3, which is1000. - Only one dot. In
"1.2.3"the second dot stops the reading, so the result is1.2. - No number, no result.
"abc"does not start with a digit, so the result isNaN.

