How to work with numbers
Use arithmetic operators
JavaScript uses one number type for most integer and decimal arithmetic.
const subtotal = 12.5 * 3;
const shipping = 4;
const total = subtotal + shipping;
console.log(total);
console.log(17 % 5); // remainder: 2
Respect precedence
Multiplication and division happen before addition and subtraction. Parentheses make intent explicit.
console.log(2 + 3 * 4); // 14
console.log((2 + 3) * 4); // 20
console.log(2 ** 3); // 8
Round and format
Math provides numeric utilities. toFixed returns a string, which is useful for display but not continued arithmetic.
const value = 7.856;
console.log(Math.round(value));
console.log(Math.floor(value));
console.log(value.toFixed(2)); // "7.86"
Handle NaN and floating point
Invalid numeric operations may produce NaN. Decimal fractions can have tiny binary rounding differences.
const result = Number("not a number");
console.log(Number.isNaN(result)); // true
console.log(0.1 + 0.2); // 0.30000000000000004
console.log((10 + 20) / 100); // 0.3