Skip to content

parseFloat stops at first non-numeric character

Quick summary

You called parseFloat on a string with trailing non-numeric text — it silently stops and returns a partial number.

Why this happens

  • Parsing CSS values like '12.5px' without stripping the unit

  • Assuming parseFloat returns NaN for any non-numeric string

  • Not checking the full string was consumed

Minimal example

✗ Broken code
const width = parseFloat('12.5px');
console.log(width); // 12.5 — silently ignores 'px'
console.log(parseFloat('abc')); // NaN — but no error thrown
✓ Fixed code
const raw = '12.5px';
const num = Number(raw.replace(/[^0-9.]/g, ''));
console.log(num); // 12.5 — explicit strip then parse

parseFloat stops at 'px' and returns 12.5 without warning, hiding the unit. Stripping non-numeric characters first makes the parse explicit and correct.

How to diagnose

  • Compare the parsed number with the original string to detect leftover text

  • Check for NaN when the string should be fully numeric

  • Use Number() which is stricter about trailing characters

How to fix

  • Strip non-numeric suffixes before parsing: parseFloat('12.5px'.replace(/[^0-9.]/g, ''))

  • Use Number() or the unary + for strict parsing that fails on trailing text

  • Validate the full string matches a numeric pattern before parsing

How to prevent

  • Use Number() when the whole string must be numeric

  • Strip units and whitespace explicitly before parseFloat

Related Resources

Related Glossary

Related Lessons

← Back to language