Numbers & Math

Published by Brayan K

Prices, scores, percentages, coordinates, timers — numbers run through every app. JavaScript has just one number type for integers and decimals alike, which is convenient until you hit the famous 0.1 + 0.2 surprise.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Keep the calculation separate from its label

Start with numeric values and calculate before turning the result into display text. A quoted number is still a string. The arithmetic operators act on values; a label such as “units” belongs in the printed message, not inside a value you intend to multiply.

const boxes = 3;
const itemsPerBox = 4;
const spareItems = 2;
const total = boxes * itemsPerBox + spareItems;
console.log(total);
console.log((boxes + spareItems) * itemsPerBox);
console.log(typeof total);

// ✅ Expected output:
// 14
// 20
// number

Multiplication happens before addition. Parentheses group a different calculation, so the two expressions deliberately answer different questions. Use parentheses when the grouping matters to the reader. ** raises a value to a power; / is division and does not automatically discard a fractional part.

console.log(17 / 5);
console.log(17 % 5);
console.log(-17 % 5);
console.log(2 ** 3);
console.log((-2) ** 2);

// ✅ Expected output:
// 3.4
// 2
// -2
// 8
// 4

The remainder operator % gives what is left after division truncated towards zero. With a negative dividend, the remainder can be negative; do not assume it always produces a nonnegative array position. The parentheses around the negative base make the exponent’s operand explicit.

A short decimal display can hide an approximation

JavaScript’s number values use binary floating point. Some fractions, such as one half, are exactly representable; many familiar decimal fractions are not. Printing a short decimal does not prove that the stored value is an exact decimal quantity.

const sum = 0.1 + 0.2;
console.log(sum);
console.log(sum === 0.3);
console.log(sum.toFixed(2));
console.log(sum);

// ✅ Expected output:
// 0.30000000000000004
// false
// 0.30
// 0.30000000000000004

toFixed produces a string for display. It does not change the original number or turn binary arithmetic into exact decimal arithmetic. Keep calculating with numeric values, and format the final result when displaying it.

const price = 2.5;
const formatted = price.toFixed(2);
console.log(typeof formatted);
console.log(formatted + 1);
console.log((price + 1).toFixed(2));

// ✅ Expected output:
// string
// 2.501
// 3.50

The addition after formatting joins text. This is a type change, not a rounding problem. Type Coercion (== vs ===) owns the detailed conversion rules behind mixed operands.

const value = 3.5;
console.log(value.toFixed(101));

// ✅ Expected error:
// RangeError: toFixed() digits argument must be between 0 and 100

The argument to toFixed is the number of digits after the decimal point, within its supported range. Increasing it does not recover decimal precision that the original number never stored. For very large magnitudes it may also use exponential notation; this method is a display tool, not a decimal storage format.

Choose rounding by direction, especially below zero

Math.floor moves towards negative infinity; Math.ceil moves towards positive infinity; Math.trunc removes the fractional part. They agree in some cases and disagree in others. Try negative input before assuming a rounding rule is correct.

const positive = 4.7;
const negative = -4.7;
console.log(Math.floor(positive), Math.ceil(positive), Math.trunc(positive));
console.log(Math.floor(negative), Math.ceil(negative), Math.trunc(negative));

// ✅ Expected output:
// 4 5 4
// -5 -4 -4

Math.round chooses the nearest integer, with an exact halfway case going towards positive infinity. That is not the same as always rounding halves away from zero, or rounding halves to the nearest even integer.

console.log(Math.round(2.5));
console.log(Math.round(-2.5));
console.log(Math.round(2.49));
console.log(Math.round(-2.51));

// ✅ Expected output:
// 3
// -2
// 2
// -3

Use the rule required by the problem. A calculation involving money, measurements or scores may specify its own rounding policy; calling a familiar Math method does not establish that policy.

Convert the whole input or deliberately read a prefix

Number attempts to convert the whole string as a numeric value. parseInt and parseFloat can accept a numeric prefix and stop at later characters. Prefix parsing is useful when that is the contract, but it is a poor substitute for checking that an entire field is a valid number.

console.log(Number(" 12.5 "));
console.log(Number("12px"));
console.log(parseInt("12px", 10));
console.log(parseFloat("12.5kg"));
console.log(parseInt("12.9", 10));
console.log(parseInt("101", 2));

// ✅ Expected output:
// 12.5
// NaN
// 12
// 12.5
// 12
// 5

The second argument to parseInt is the radix: the base used to interpret the digits. Specify it when parsing integers. Parsing a decimal-looking string as an integer is not rounding it to the nearest integer; the parser stops when the fractional part begins.

const raw = "   ";
const value = Number(raw);
console.log(raw.trim() === "");
console.log(value);
console.log(Number.isFinite(value));
console.log(Number.isFinite("12"));

// ✅ Expected output:
// true
// 0
// true
// false

An empty or whitespace-only string converts to zero. That may be unacceptable for a required field even though zero is finite. Decide whether empty input is allowed separately from conversion. Number.isFinite checks the value it receives without converting a string first; Conditionals & Operators owns using such checks to accept or reject a value.

Not every number is a usable finite result

Ordinary number arithmetic can produce NaN or infinity without throwing an exception. A program continuing to run does not prove its numeric result is useful. Check the property the application needs: finite, integer or safe integer.

const invalid = 0 / 0;
const unbounded = 1 / 0;
console.log(invalid);
console.log(unbounded);
console.log(typeof invalid);
console.log(invalid === NaN);
console.log(Number.isNaN(invalid));
console.log(Number.isFinite(unbounded));

// ✅ Expected output:
// NaN
// Infinity
// number
// false
// true
// false

NaN means “not a number”, but it is a special value of the number type. It is not equal to itself, so comparing a result with NaN using === cannot detect it. Number.isNaN answers that question directly. Number.isFinite excludes both NaN and infinities.

const limit = Number.MAX_SAFE_INTEGER;
console.log(Number.isSafeInteger(limit));
console.log(Number.isSafeInteger(limit + 1));
console.log(limit + 1 === limit + 2);
console.log(Number.isInteger(3.5));
console.log(Number.isInteger(3));

// ✅ Expected output:
// true
// false
// true
// false
// true

Beyond the safe integer range, distinct mathematical integers can collapse to the same number value. Some individual larger integers are representable, but consecutive integer arithmetic is no longer reliably exact. BigInt & Number Precision owns exact large-integer arithmetic and its boundaries; BigInt is a separate type, not a way to make decimal fractions exact.

Use the Math operation that matches the question

Math methods are called on Math itself. They cover different questions: distance from zero, the smallest supplied value, the largest supplied value and a square root. A method may still return NaN when its input is outside the real-number result it can represent.

console.log(Math.abs(-7));
console.log(Math.min(8, 3, 5));
console.log(Math.max(8, 3, 5));
console.log(Math.sqrt(81));
console.log(Number.isNaN(Math.sqrt(-1)));

// ✅ Expected output:
// 7
// 3
// 8
// 9
// true

A random draw should not have a fixed expected value. For a repeatable example, supply the fractional sample yourself and inspect the mapping into a small range of indices. A real Math.random() sample is at least zero and below one; it is unsuitable for security-sensitive randomness.

function indexFromSample(sample, size) {
  return Math.floor(sample * size);
}
console.log(indexFromSample(0, 4));
console.log(indexFromSample(0.5, 4));
console.log(indexFromSample(0.999, 4));

// ✅ Expected output:
// 0
// 2
// 3

This helper assumes a sample in the documented range and a positive integer size. Multiplying scales the range; floor chooses its integer bucket. Using round would give different edge behaviour. The samples here are fixed test inputs, not a claim that a random generator repeats these values.

Complete a calculation before formatting it

A pack contains three items, each priced at 125 minor units. Fill the blanks to calculate the total in minor units and format the corresponding major-unit amount to two decimal places. The hints give the exact expressions; leave formatting until the calculation is complete.

const unitPrice = 125;
const quantity = 3;
const total = ___; // 👉 replace ___ with unitPrice * quantity
const display = ___; // 👉 replace ___ with (total / 100).toFixed(2)
console.log(total);
console.log(display);
console.log(typeof display);

// ✅ Expected output:
// 375
// 3.75
// string

Integer minor units keep these particular multiplication and addition steps exact while values remain within the safe integer range. They do not remove the need to define rounding for percentage charges or fractional units.

Prepare a small order summary

Given the quantity text "4", a unit price of 235 minor units and a fixed packing charge of 60 minor units, convert the quantity, calculate the total, and print the quantity, total minor units and a two-decimal display amount on separate lines. Use these fixed valid inputs; input rejection belongs to a separate decision step.

const quantityText = "4";
const unitPrice = 235;
const packingCharge = 60;
const quantity = Number(quantityText);
const total = quantity * unitPrice + packingCharge;
console.log(quantity);
console.log(total);
console.log((total / 100).toFixed(2));

// ✅ Expected output:
// 4
// 1000
// 10.00

Change the quantity and rerun it. Then try empty quantity text and inspect why conversion alone accepts it. The required-field check and the calculation answer different questions; keeping them separate makes the mistake easier to find.

References: Number, Math.round, and toFixed in MDN.

Practice quiz

What does this complete program print? console.log(2 + 3 * 4);

  • 14
  • 20
  • 24
  • 9

Answer: 14. Multiplication is evaluated before addition; parentheses would be needed to add first.

What does this complete program print? const value = 2.5; console.log(value.toFixed(2) + 1);

  • 3.50
  • 2.501
  • 3.5
  • 2.51

Answer: 2.501. toFixed returns text, so the later + joins the string and the converted right operand.

What does this complete program print? console.log(Math.floor(-4.7), Math.trunc(-4.7));

  • -4 -4
  • -5 -5
  • -5 -4
  • -4 -5

Answer: -5 -4. Floor moves towards negative infinity; trunc removes the fractional part towards zero.

What does this complete program print? console.log(Math.round(-2.5));

  • -3
  • -2.5
  • 3
  • -2

Answer: -2. An exact halfway value rounds towards positive infinity.

What does this complete program print? console.log(Number("12px")); console.log(parseInt("12px", 10));

  • NaN 12
  • 12 12
  • NaN NaN
  • 12 NaN

Answer: NaN 12. Number requires the whole numeric string; parseInt can stop after the valid integer prefix.

What does this complete program print? console.log(Number.isFinite(Number(" ")));

  • false
  • true
  • NaN
  • TypeError

Answer: true. Whitespace-only text converts to zero, so a finite-number check alone does not reject an empty field.

What does this complete program print? const result = 0 / 0; console.log(result === NaN); console.log(Number.isNaN(result));

  • true true
  • false false
  • false true
  • true false

Answer: false true. NaN cannot be detected with equality to NaN; Number.isNaN tests it directly.

What does this complete program print? const limit = Number.MAX_SAFE_INTEGER; console.log(limit + 1 === limit + 2);

  • false
  • RangeError
  • undefined
  • true

Answer: true. Above the safe range, consecutive mathematical integers can be represented by the same number value.

Continue this course

Related lessons