Skip to content
Tutorials Center
My learning

Topics

Lesson 155 of 156 ยท Practice and Review

Number and Math Recipes

JavaScript number recipes with live examples: mean, median, standard deviation, GCD and LCM, binomial coefficients, rounding to a multiple, float comparison and base conversion.

The Math object gives you rounding, powers and trigonometry, but not the everyday helpers: the median of a list, the greatest common divisor, "round to the nearest 5". You write those yourself, and they are short.

This lesson collects the recipes you will reach for most. Along the way you will meet the traps of floating point numbers (see Numbers for why 0.1 + 0.2 is not 0.3) and the habits that avoid them.

Statistics: mean, median, standard deviation

The mean adds the values and divides by how many there are. The median is the middle value of the sorted list, or the average of the two middle values when the count is even. The standard deviation measures how far values typically sit from the mean: small means the numbers cluster together.

Always sort a copy for the median, and give numbers a comparison function, because the default sort() compares as text.

JS Mean, median, standard deviation, RMS

Press Run (or Ctrl + Enter) to see the console output here.

No output.

An empty list gives NaN for the mean (0 divided by 0), so check list.length first if your data can be empty.

GCD and LCM

The greatest common divisor (GCD) of two integers is the largest number that divides both. Euclid's algorithm finds it by replacing the pair (a, b) with (b, a % b) until the second number is zero. The least common multiple (LCM) follows from the GCD: a * b / gcd(a, b).

JS GCD, LCM and simplifying fractions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Take care with huge numbers: a * b can exceed the safe integer range. Divide first (a / gcd(a, b) * b) or use BigInt.

Quotient, remainder and rounding to a multiple

Integer division has two parts: the quotient (how many whole times) and the remainder (what is left). % gives the remainder, and Math.trunc(a / b) gives the quotient. For negative numbers, % keeps the sign of the first number, which surprises many people; a "proper" modulo that is never negative needs one more step.

Rounding to a multiple divides, rounds and multiplies back: prices to the nearest 0.05, sizes to the next multiple of 8.

JS divmod, modulo and round to multiple

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Comparing floating point numbers

Because most decimals cannot be stored exactly, two results that should be equal can differ by a tiny amount. Compare with a tolerance instead of ===. Number.EPSILON is the gap between 1 and the next representable number. It is a good tolerance for values near 1, but too small for large numbers, so scale it, or use a relative error.

JS Approximate equality

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For currency, store integer cents (or use Intl.NumberFormat only for display) and convert at the edges.

Binomial coefficients and factorials

The binomial coefficient "n choose k" counts the ways to pick k items from n when order does not matter: lottery draws, team selections, the entries of Pascal's triangle. Computing factorials first overflows quickly. Multiply and divide step by step instead, so numbers stay small and every intermediate result is an integer.

JS Factorial and n choose k

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Converting between number bases

number.toString(radix) writes a number in any base from 2 to 36, and parseInt(text, radix) reads one back. Always pass the radix to parseInt, because without it a string like "0x1F" is read as hexadecimal and older code could misread a leading zero. Prefix literals exist too: 0b1010 (binary), 0o17 (octal) and 0xff (hex).

JS toString(radix) and parseInt(radix)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For arbitrarily large numbers, BigInt also accepts toString(radix); see BigInt and Symbol.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does [10, 9, 1].sort() return, and why?

    Without a comparison function, sort converts items to strings, so "10" comes before "9". Pass (a, b) => a - b to sort numbers.
  2. 2. What is gcd(48, 18) with Euclid's algorithm, and what is the first step?

    48 % 18 is 12, so (48, 18) becomes (18, 12), then (12, 6), then (6, 0). The answer is 6.
  3. 3. What does -17 % 5 evaluate to in JavaScript?

    The remainder takes the sign of the first operand. Use ((a % b) + b) % b for a modulo that is never negative; it gives 3 here.
  4. 4. Which is the best way to compare the results of floating point arithmetic?

    Binary floating point cannot store most decimals exactly, so equal-looking results can differ by a tiny amount. A tolerance check handles that.
  5. 5. Why should you always pass the second argument to parseInt?

    parseInt("0x1F") reads hexadecimal because of the prefix. Writing parseInt(text, 10) leaves no doubt about the base.

Summary

  • Sort a copy with (a, b) => a - b for the median; the mean of an empty list is NaN.
  • Standard deviation divides by n for a population and by n - 1 for a sample.
  • Euclid's algorithm gives the GCD; the LCM is a / gcd * b. Beware of overflow past 2^53.
  • % keeps the sign of the first operand; ((a % b) + b) % b always lands in 0 ... b - 1.
  • Round to a multiple with Math.round(n / step) * step.
  • Compare floats with a tolerance, and keep money in integer cents.
  • Build n choose k step by step to avoid huge factorials.
  • toString(radix) and parseInt(text, radix) convert between bases; always pass the radix.

Next: JavaScript Practice Exercises.