Round to the nearest 5 or 0.05 in JavaScript
Intermediate · 4 min read
Math.round only rounds to a whole number. Real apps usually want something else: a price to two decimal places, a distance to one, a total to the nearest ₦50 or ₦1000, a chart axis to the nearest 5.
In this tutorial you will write two small functions. round(n, places) rounds to a number of decimal places and returns a number. toNearest(n, step) rounds to the nearest 5, 50, 1000 or any other step. Then you will find the input that fools the first one. You need to know Math.round and the ** power operator.
The trick: scale, round, scale back
Math.round can't round 3.14159 to two places directly. But it can round a whole number, so you move the decimal point out of the way first:
- Multiply by 100: 3.14159 becomes 314.159.
- Round: 314.159 becomes 314.
- Divide by 100: 314 becomes 3.14.
For one decimal place you would use 10, for three you would use 1000. In general the number is 10 ** places.
Rounding to a step
Rounding to the nearest 5 is the same trick turned around. Ask "how many fives is this?", round that count, then multiply back. 13 is 2.6 fives, which rounds to 3 fives, which is 15.
Here is the exercise. Have a go first if you like, then read on and we will build it together.
7 Round to a given number of decimal places
fairWrite round(n, places) returning a number. Then write toNearest(n, step) that rounds to the nearest 5, 50 or 1000. Then find the input that defeats the scaling trick.
Stuck? Three hints, smallest first
- 1. Scale up by
10 ** places, round, scale back down. - 2. Rounding to the nearest step is
Math.round(n / step) * step. - 3.
1.005is stored slightly below 1.005, so scaling by 100 lands under the halfway point.
Step 1: round to two places
const round = (n, places = 0) => {
const factor = 10 ** places;
return Math.round(n * factor) / factor;
};
console.log(round(3.14159, 2)); // 3.14
console.log(round(-3.14159, 3)); // -3.142
console.log(round(2.5)); // 3
places = 0 is a default value: if you call round(2.5) without a second argument, places is 0, factor is 10 ** 0, which is 1, and you get an ordinary Math.round.
The result is a real number, not text:
const round = (n, places = 0) => Math.round(n * 10 ** places) / 10 ** places;
console.log(typeof round(3.14159, 2)); // number
That means you can keep doing math with it. You will see in the next exercise that toFixed gives you text instead.
Step 2: the input that breaks it
Try 1.005. Rounded to two places, you would expect 1.01.
const round = (n, places = 0) => Math.round(n * 10 ** places) / 10 ** places;
console.log(round(1.005, 2)); // 1
console.log(1.005 * 100); // 100.49999999999999
You get 1. Here is why. Computers store decimals in binary, and most decimals, like 1.005, can't be stored exactly. JavaScript keeps the closest value it can, which is a tiny bit below 1.005. Multiplied by 100 it lands just under 100.5, so Math.round correctly rounds it down.
No rounding function that works on ordinary JavaScript numbers can fully avoid this, because the digit you wanted was never stored. When money must be exact to the kobo, keep amounts as whole numbers of kobo instead (exercise 15). For display, this trick is the right default.
Step 3: round to the nearest step
const toNearest = (n, step) => Math.round(n / step) * step;
console.log(toNearest(13, 5)); // 15
console.log(toNearest(1234, 50)); // 1250
console.log(toNearest(1499999, 1000)); // 1500000
n / step counts how many steps fit, Math.round picks the nearest whole count, and * step turns that count back into a value. 1234 divided by 50 is 24.68, which rounds to 25, and 25 times 50 is 1250.
Step 4: a decimal step like 0.05
Rounding a price to the nearest 5 kobo means a step of 0.05. Try toNearest with it:
const toNearest = (n, step) => Math.round(n / step) * step;
console.log(toNearest(1.23, 0.05)); // 1.25
console.log(toNearest(0.33, 0.05)); // 0.35000000000000003
The first looks fine. The second has a tail of junk digits, because 0.05 can't be stored exactly either, and multiplying by it brings the error back.
The fix is to divide by a whole number at the end. Rounding to 0.05 is the same as rounding to a twentieth, so multiply by 20, round, and divide by 20:
console.log(Math.round(0.33 * 20) / 20); // 0.35
Dividing by a whole number gives the closest stored value to the answer, which prints cleanly. It is the same idea as round(n, places), where you also divide by a whole number.
The full solution
The answer panel has round and toNearest, shows round(1.005, 2) coming out as 1, and prints 1.005 * 100 so you can see why. The checks underneath confirm every value, including rounding to the nearest ₦1000. Press Run to see the output.
const round = (n, places = 0) => {
const factor = 10 ** places;
return Math.round(n * factor) / factor;
};
const toNearest = (n, step) => Math.round(n / step) * step;
console.log('round(3.14159, 2) :', round(3.14159, 2));
console.log('round(2.5) :', round(2.5));
console.log('round(-3.14159, 3):', round(-3.14159, 3));
console.log('round(1.005, 2) :', round(1.005, 2), '<- expected 1.01');
console.log('why: 1.005 * 100 =', 1.005 * 100, '<- just under 100.5');
console.log('nearest 50 of 1234:', toNearest(1234, 50));
console.log('nearest 1000 naira:', toNearest(1499999, 1000));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('two decimal places', round(3.14159, 2), 3.14);
test('no places is an ordinary round', round(2.5), 3);
test('negatives scale the same way', round(-3.14159, 3), -3.142);
test('the result is a number, not a string', typeof round(3.14159, 2), 'number');
test('but 1.005 rounds down to 1, not up to 1.01', round(1.005, 2), 1);
test('because scaling it lands a hair under the halfway point', 1.005 * 100, 100.49999999999999);
test('to the nearest 5', toNearest(13, 5), 15);
test('to the nearest 50', toNearest(1234, 50), 1250);
test('and to the nearest 1000 naira', toNearest(1499999, 1000), 1500000);
The scale-round-unscale trick is the right default, and it is not exact. It cannot be: 1.005 is not in the set of doubles, the nearest one is 1.00499999999999989..., and no amount of arithmetic recovers a digit that was never stored. Every decimal-rounding routine written in binary floating point has an input like this.
If the two-places answer must be right for money, do not round a float at all — hold kobo as integers (exercise 15) and divide only when printing. If it only has to look right, toFixed in exercise 8 rounds the decimal expansion and gets 1.005 wrong in the same direction, for the same reason.
toNearest is the more useful half of this exercise: pricing to the nearest ₦50, bucketing a chart axis, snapping a value to a grid.
Common mistakes
- Dividing before rounding.
Math.round(n / 100) * 100rounds to the nearest hundred, not to two decimal places. For places, multiply first. - Expecting 1.005 to become 1.01. The stored value is just under 1.005. For exact money, use whole numbers of kobo.
- Multiplying by a decimal step at the end.
Math.round(n / 0.05) * 0.05can print junk digits. UseMath.round(n * 20) / 20.
Try it yourself
- Round 2.71828 to one, two and three places with your
round. - Round 87, 92 and 95 to the nearest 10. Which way does 95 go, and why?
- Write
roundToHalf(n)that rounds to the nearest 0.5, so 3.3 becomes 3.5 and 3.2 becomes 3.