Deliberate Numeric Parsing With Number And parseInt

Number rejects any extra characters while parseInt and parseFloat consume leading digits; explicit radix and isFinite checks keep numeric input parsing strict.

JavascriptData Integrity

Code

javascriptsnippet
19 lines
// Number converts the whole string: any extra character means NaN (leading/trailing whitespace allowed)
console.log('Number     :', Number('42'), Number('42px'), Number(' 7 '), Number(''));

// parseInt consumes only the leading characters the radix can explain: always pass the radix explicitly
console.log('parseInt   :', parseInt('42px', 10), parseInt('0x1f', 16), parseInt('12', 3));

// parseFloat accepts decimals and exponents but likewise stops at the first invalid character
console.log('parseFloat :', parseFloat('12.5rem'), parseFloat('3e2zz'));

// empty-string trap: Number('') is 0, so empty form input must be ruled out first
const raw = '';
console.log('empty str  :', Number(raw), '| isFinite:', Number.isFinite(Number(raw)));

// the parsing boundary: invalid input returns NaN explicitly instead of a silent 0
function toQuantity(input) {
  const value = Number(input);
  return input !== '' && Number.isFinite(value) ? value : NaN;
}
console.log('toQuantity :', toQuantity('8'), toQuantity('abc'), toQuantity(''));

How the snippet works

Deliberate Numeric Parsing With Number And parseInt is built around the function toQuantity.

Using it

Signature: function toQuantity(input)

The demo output is labeled (Number :, parseInt :, parseFloat :), so every printed line maps back to its originating operation.

Key statements

return input !== '' && Number.isFinite(value) ? value : NaN;

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `toQuantity` at load time.