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.
Code
// 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
Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Number FormatterFormat numbers with thousands grouping, fixed decimals, custom separators, and an optional prefix or suffix.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.Phone Number FormatterNormalize a phone number with an optional country code into E.164, RFC 3966, and grouped national formats, with digit-count validation.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.