Hiprup

How do you convert a string to a number in JavaScript?

Several ways, each with trade-offs:

  • Number(str) — strict, full-string conversion.

  • parseInt / parseFloat — extract leading numbers from mixed strings.

  • Unary plus (+str) — concise; behaves like Number().

  • Watch out — empty strings become 0 with Number(), and invalid input gives NaN.

Always validate with Number.isNaN before trusting the result.

const str = '42.5';

// 1. Number() — strict, full conversion
Number('42.5')     // 42.5
Number('42px')     // NaN
Number('')         // 0

// 2. Unary + — same as Number()
+'42.5'            // 42.5
+'42px'            // NaN

// 3. parseInt() — integer, stops at non-digit
parseInt('42.5')   // 42 (drops decimal)
parseInt('42px')   // 42 (stops at 'p')

// 4. parseFloat() — float, stops at non-digit
parseFloat('42.5px') // 42.5

// 5. Math.floor/ceil/round — via implicit conversion
Math.floor('42.9')   // 42
Math.round('42.5')   // 43

// Summary:
// Need strict conversion → Number() or +
// Need to extract number from string → parseInt/parseFloat
// Need integer → parseInt or Math.floor(Number(str))

Number and + require the full string to be numeric. parseInt/parseFloat extract numbers from the start of strings. parseInt drops decimals, parseFloat keeps them. Choose based on strictness: Number for validation (NaN on invalid), parseInt for extraction (ignores trailing text).

Know all 5 methods and when each is appropriate. Number/+ for strict validation. parseInt/parseFloat for extraction from mixed strings.

The practical choice: Number for forms (validate), parseInt for CSS values ('42px' → 42).

How do you convert a string to a number in JavaScript? | Hiprup