Math and rounding

Math is a namespace of functions and constants over the number type, and the rounding functions are the ones a program reaches for every day: a page count, a score, a price in cents and a value on a scale all need a decision about the fraction. The four functions in the first section differ only in the direction they round, and the difference appears as soon as the value is negative.

This lesson prints the four directions side by side on the same values, then the pair min and max with their empty-argument answers, Math.random which returns a value nobody can predict, and a helper that rounds to a number of decimals. The random part prints the range of the value and never the value itself, because a page whose output changes cannot be checked.

round, floor, ceil and trunc

Math.round goes to the nearest integer, and a value exactly halfway goes up: towards positive infinity, not away from zero. Math.floor always goes down, Math.ceil always goes up and Math.trunc drops the fraction towards zero. For positive values floor and trunc agree, and for negative values they do not.

const values = [2.5, 2.4, -2.5, -2.4]; for (const value of values) { console.log( value, 'round:', Math.round(value), 'floor:', Math.floor(value), 'ceil:', Math.ceil(value), 'trunc:', Math.trunc(value) ); }

node directions.js

2.5 round: 3 floor: 2 ceil: 3 trunc: 2
2.4 round: 2 floor: 2 ceil: 3 trunc: 2
-2.5 round: -2 floor: -3 ceil: -2 trunc: -2
-2.4 round: -2 floor: -3 ceil: -2 trunc: -2

The third line is the one to remember: minus two and a half rounds to minus two, because the halfway case goes up and up means towards positive infinity. Math.floor(-2.4) is minus three, which is correct for a floor and wrong for a magnitude, so a program that rounds a negative amount with floor moves it away from zero. The half-up rule of round is also not the half-up rule of an accounting system, which rounds halves away from zero.

min, max and the rest of the object

Math.max reads its arguments, not an array, and returns the largest of them. Called with nothing it returns -Infinity, which is the identity of the operation: the value that loses against everything. A single NaN among the arguments makes the whole answer NaN, because a comparison with NaN is always false.

console.log('max:', Math.max(3, 9, 4)); console.log('min:', Math.min(3, 9, 4)); console.log('max of nothing:', Math.max()); console.log('min of nothing:', Math.min()); console.log('max of an array:', Math.max(...[3, 9, 4])); console.log('abs:', Math.abs(-7)); console.log('pow:', Math.pow(2, 10), 2 ** 10); console.log('sqrt:', Math.sqrt(144)); console.log('NaN wins:', Math.max(1, NaN, 3));

node minmax.js

max: 9
min: 3
max of nothing: -Infinity
min of nothing: Infinity
max of an array: 9
abs: 7
pow: 1024 1024
sqrt: 12
NaN wins: NaN

The empty calls are useful in a loop that starts with the identity and takes a maximum of what it has seen: the first value always wins against -Infinity. The array case needs the spread of the previous part, because the function has no array overload, and 2 ** 10 is the operator that replaced most uses of Math.pow.

random and its range

Math.random returns a number from zero up to but not including one, and the sequence cannot be seeded: there is no argument that makes the next call predictable. The program below builds five rolls of a die and then checks the properties of the results instead of printing them, so the output is the same on every run. The value of one call is printed as a comparison only.

function die(sides) { return Math.floor(Math.random() * sides) + 1; } const rolls = []; for (let i = 0; i < 5; i += 1) { rolls.push(die(6)); } const sample = Math.random(); console.log('rolls:', rolls.length); console.log('all integers:', rolls.every((roll) => Number.isInteger(roll))); console.log('all from 1 to 6:', rolls.every((roll) => roll >= 1 && roll <= 6)); console.log('sample in [0, 1):', sample >= 0 && sample < 1);

node random.js

rolls: 5
all integers: true
all from 1 to 6: true
sample in [0, 1): true

The multiplication stretches the interval to six units and the floor cuts it into six equal parts, so the addition of one moves the range to one through six. The numbers are not uniform enough for a lottery or a password: the generator is a fast statistical one and its state can be recovered from its output. A test that needs a fixed sequence takes a small generator of its own, or the seed option of a library, because the language offers no seed.

Rounding to a number of decimals

There is no Math.roundTo. The usual helper multiplies by a power of ten, rounds and divides back, and it inherits the floating point of the first lesson of this part: a value that looks like a halfway case may be stored just below it. The program shows both the cases that work and the one that surprises, then does a percentage with integers, which is the exact way.

function roundTo(value, digits) { const factor = 10 ** digits; return Math.round(value * factor) / factor; } console.log('3.14159 to 2:', roundTo(3.14159, 2)); console.log('2.675 to 2:', roundTo(2.675, 2)); console.log('1.005 to 2:', roundTo(1.005, 2)); console.log('-1.5 to 0:', roundTo(-1.5, 0)); console.log('10 to 1:', roundTo(10, 1)); const price = 1999; const vat = Math.round((price * 20) / 100); console.log('vat in cents:', vat); console.log('total in cents:', price + vat);

node decimals.js

3.14159 to 2: 3.14
2.675 to 2: 2.68
1.005 to 2: 1
-1.5 to 0: -1
10 to 1: 10
vat in cents: 400
total in cents: 2399

2.675 rounded up and 1.005 rounded down, and both followed the stored value rather than the decimal in the source. The last two lines are the pattern that does not have the problem: the amount stays an integer of cents, the percentage is computed on integers and the division happens once, when the value is printed. A rounding helper is fine for a chart; money takes integers.

Exercises

  1. Add -0.5 to the array in directions.js. Which of the four functions return -0, and how does Object.is(-0, 0) answer?
  2. Call Math.max() with one argument, then with an array and no spread. Which output line changes, and what does the array case return?
  3. Change the die in random.js to twenty sides and print Math.min(...rolls) and Math.max(...rolls). Why are those two lines safe to print?
  4. Round -2.5 with roundTo(-2.5, 0). Which value arrives, and which rounding rule does that show?
  5. Compute a discount of fifteen percent on 1999 cents in decimals.js. Which integer do you get, and how would you round it up to the next cent instead?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does Math.round(-2.5) return?

    Answer

    -2

    A halfway case rounds towards positive infinity, so minus two and a half becomes minus two.

  2. What does Math.floor(-2.4) return?

    Answer

    -3

    The floor is the largest integer that is not above the value, which is minus three.

  3. How do Math.floor and Math.trunc differ?

    Answer

    They agree on positive values and differ on negative ones

    floor goes down and trunc goes towards zero, and for a negative value those are two different directions.

  4. What does this program print? console.log(Math.max());

    Answer

    -Infinity

    The empty maximum is the identity of the operation, and minus infinity loses against every number.

  5. What does this program print? console.log(Math.max(1, NaN, 3));

    Answer

    NaN

    Every comparison with NaN is false, so the maximum cannot be decided and the answer is NaN.

  6. What range does Math.random() return?

    Answer

    From 0 up to but not including 1

    The value is a fraction below one, which is why the multiply-and-floor recipe works.

  7. Why does this lesson print the result of Math.random() only as a comparison?

    Answer

    Because the value changes on every run, so the printed page could not be checked

    A page shows the output of one run, and a random value would make the next run disagree with it.

  8. What does this program print? console.log(Math.round(2.5), Math.round(3.5));

    Answer

    3 4

    Both halves go up, so the two results are the next integer above each value.

  9. What is the exact way to compute a percentage of a money amount?

    Answer

    Keep the amount in cents and round the integer result

    Integer cents keep every step exact, and the single division happens at the point of printing.

  10. What does this program print? console.log(Math.trunc(-2.7));

    Answer

    -2

    Truncation drops the fraction towards zero, so the value moves up towards zero.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev