
A quantity field contains 12px, yet an import accepts it as 12. Adding radix 10 to parseInt does not solve that problem. The function parses a valid integer prefix; it does not require the entire field to be an integer.
I separate two questions: which text formats does this field permit, and can the chosen JavaScript number type represent the accepted value safely? Converting first and checking later can lose the evidence needed to answer the first question.
Watch where parsing stops
Run these small examples:
console.log(parseInt("12px", 10)); // 12
console.log(parseInt("1.9", 10)); // 1
console.log(parseInt("1e3", 10)); // 1
console.log(Number("12px")); // NaN
console.log(Number("")); // 0
console.log(Number("1e3")); // 1000 The unit suffix, decimal point and exponent stop the base-10 integer parser. It returns the prefix it understood. That is useful when prefix parsing is intentional, but it is a poor validator for a field that must contain only a complete integer.
Number rejects the unit suffix, but it is not a drop-in validation policy either. An empty string becomes zero, while exponent notation is accepted. A successful conversion only tells you that the conversion rules accepted the input, not that your application should.
Write down the field contract
For this example, I allow a string containing an optional sign and one or more ASCII decimal digits. Surrounding whitespace is trimmed. Leading zeros are allowed. Decimal fractions, exponents, units, separators and hexadecimal notation are not. The result must fit within JavaScript's safe integer range.
This is a deliberate policy for a small integer field, not a universal number parser. Continue with:
function readInteger(raw) {
if (typeof raw !== "string") {
throw new TypeError("Expected a string");
}
const text = raw.trim();
if (!/^[+-]?[0-9]+$/.test(text)) {
throw new SyntaxError("Expected decimal integer digits");
}
const value = Number(text);
if (!Number.isSafeInteger(value)) {
throw new RangeError("Integer outside safe Number range");
}
return value;
}
console.log(readInteger(" +12 ")); // 12
console.log(readInteger("-3")); // -3
console.log(readInteger("007")); // 7 The type check prevents values such as null and booleans from entering through implicit conversion. The regular expression checks the complete trimmed text before conversion. The final check rejects values outside the safe integer range, including integers that might otherwise be rounded.
Radix 10 alone would not provide these guarantees. Neither would calling Number.isInteger on the result of parseInt: the unwanted suffix has already disappeared by then.
Test rejected values as well as happy paths
Keep the function above and run:
const rejected = [
"", " ", "12px", "1.9", "1e3",
"0x10", "1_000", "9007199254740993"
];
for (const input of rejected) {
try {
console.log("accepted", readInteger(input));
} catch (error) {
console.log(JSON.stringify(input), error.name);
}
} The first seven entries raise SyntaxError; the large integer raises RangeError. Those distinctions can help an interface explain whether the problem is format or size. In a real import, attach the field name and record position without logging sensitive source values unnecessarily.
Do not accidentally change what the field means
An account code such as 007 may need to stay a string. Turning it into 7 destroys its formatting. This example also accepts -0, which JavaScript can distinguish from positive zero. Reject or normalize it explicitly if your contract requires that.
For a nonnegative quantity, add an application range check after parsing. A safe integer can still be an invalid age, stock count or retry limit. Browser validation is also not a substitute for checking the value where it is received and used.
If you need larger exact integers, consider a separately specified BigInt path and its storage and serialization rules. Do not silently switch return types inside this helper. Decimal money, localized number formats and non-ASCII digits need different rules, not a more permissive patch to this example.
What I checked
I ran all three displayed blocks with Node.js v22.23.4 on synthetic inputs. Additional assertions covered zero, negative zero, both safe-integer limits, values just outside those limits and non-string input. These checks establish the shown behavior in that runtime, not a production audit or a cross-browser test suite.
Sources: MDN's parseInt reference, Number conversion reference and Number.isSafeInteger reference.
Comments
Post a Comment