Sub topic 2
Turning Strings into Numbers, Validating, Formatting, and Rounding
This chapter assumes you know basic JavaScript syntax, ===, typeof, and how NaN and the safe integer range behave.
Converting Strings to Numbers
Number() and unary plus (+) are strict. After trimming whitespace, the whole string must be numeric. parseInt and parseFloat read a leading numeric prefix and stop at the first invalid character.
console.log(Number("42")); // 42
console.log(Number("42px")); // NaN
console.log(Number("")); // 0
console.log(Number(null)); // 0
console.log(Number(undefined)); // NaN
console.log(+" 12 "); // 12
console.log(parseInt("42px", 10)); // 42
console.log(parseInt("1F", 16)); // 31
console.log(parseFloat("3.14abc")); // 3.14
console.log(parseInt("1e3", 10)); // 1 (stops at "e")
console.log(Number("1e3")); // 1000Always pass a radix to parseInt. The radix is the number base to parse in, such as 10 or 16. A common bug is Number("") returning 0, so empty form fields silently become zero.
Validating Results
| Method | True when |
|---|---|
| `Number.isNaN(x)` | `x` is the NaN value itself |
| `Number.isFinite(x)` | `x` is a number and not ±Infinity or NaN |
| `Number.isInteger(x)` | `x` is a number with no fractional part |
| `Number.isSafeInteger(x)` | `x` is an integer within ±(2^53 − 1) |
These Number.* methods never coerce their argument. The global functions isNaN and isFinite do coerce it.
console.log(isFinite("5")); // true (coerced)
console.log(Number.isFinite("5")); // false
console.log(Number.isInteger(5.0)); // true
console.log(Number.isSafeInteger(2 ** 53)); // falseFormatting for Display
console.log((255).toString(16)); // "ff"
console.log((0.000123).toPrecision(2)); // "0.00012"
console.log((1.005).toFixed(2)); // "1.00" (stored slightly below 1.005)
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
console.log(usd.format(1234.5)); // "$1,234.50"The Math Object and Rounding
Math is a built-in object of constants (Math.PI, Math.E) and static functions. You never construct it with new.
console.log(Math.round(2.5)); // 3
console.log(Math.round(-2.5)); // -2 (ties round toward +Infinity)
console.log(Math.floor(-2.5)); // -3
console.log(Math.ceil(-2.5)); // -2
console.log(Math.trunc(-2.5)); // -2floor and trunc give the same result for positive numbers. They differ for negative numbers: floor rounds down toward −Infinity, and trunc drops the fractional part, which moves the value toward zero.
Exercise
A user types "" into a quantity field. Your code runs const qty = Number(input); if (!Number.isNaN(qty)) save(qty);. What gets saved, and how would you fix it?
Show answer
Number("") returns 0, so the code saves 0 even though the user entered nothing. Reject empty input first by checking input.trim() === "". Then validate the result with Number.isInteger(qty).
Exercise
What do Math.floor(-3.7) and Math.trunc(-3.7) return?
Show answer
Math.floor(-3.7) returns -4, and Math.trunc(-3.7) returns -3.