Round half to even (banker's rounding) in JavaScript
Advanced · 4 min read
When money is calculated, amounts often land exactly halfway between two whole numbers: 2.5 kobo of interest, a price split three ways, a discount of half a naira. Something has to decide which way that half goes. Do it the same way every time and, over thousands of rows, the totals drift away from the truth.
In this tutorial you will write two rounding functions. halfUp rounds halves away from zero, the same way for negative and positive numbers. halfEven sends each half to the nearest even number, the rule often called banker's rounding. Then you'll measure how far each one drifts. You need to know functions, %, map and reduce.
What a tie is
A number is a tie when it sits exactly halfway between two whole numbers. 2.5 is a tie between 2 and 3. 2.4 and 2.6 are not ties: 2.4 is clearly closer to 2, and 2.6 is clearly closer to 3. Every rounding rule agrees on those. Rounding rules only differ on ties.
How Math.round handles a tie
Math.round rounds a tie towards positive infinity, which means "upwards on the number line":
console.log(Math.round(2.5)); // 3
console.log(Math.round(-2.5)); // -2
For 2.5, upwards means 3, which is what most people expect. For -2.5, upwards means -2, because -2 is higher than -3. So the two halves are not mirror images. If a column holds both payments and refunds, every tie is pushed the same way.
Here is the exercise. Try it on your own first if you like, or read on and we will build it together.
145 Rounding a half, and which way the money goes
hardMath.round sends every exact half upwards, which means -2.5 becomes -2 and a column of halves all drift the same way. Write a symmetric half-up rounder and a half-to-even one, and measure the drift each produces over a set of halves.
Stuck? Three hints, smallest first
- 1.
Math.roundrounds towards positive infinity on a tie, so it is not symmetric about zero. - 2. Round the absolute value and put the sign back for symmetric half-up.
- 3. Half-to-even only changes anything when the fraction is exactly 0.5 and the rounded result is odd.
Step 1: symmetric half-up
To make negatives mirror positives, round the size of the number and put the minus sign back afterwards:
const halfUp = (x) => (x < 0 ? -Math.round(-x) : Math.round(x));
console.log(halfUp(2.5)); // 3
console.log(halfUp(-2.5)); // -3
console.log(halfUp(2.4)); // 2
For -2.5, -x is 2.5, Math.round gives 3, and the leading minus makes it -3. Positive numbers go straight to Math.round.
Step 2: spot a tie
To treat ties differently, we first need to recognize one. x % 1 gives the part after the decimal point:
console.log(2.5 % 1); // 0.5
console.log(-2.5 % 1); // -0.5
console.log(Math.abs(-2.5 % 1)); // 0.5
console.log(Math.abs(2.4 % 1) === 0.5); // false
For a negative number, the remainder keeps the minus sign. Math.abs removes it, so one check, Math.abs(x % 1) === 0.5, works for both signs.
Step 3: half to even
Now the rule: if it's a tie and Math.round gave an odd number, step down by one to the even neighbor.
function halfEven(x) {
const rounded = Math.round(x);
const isTie = Math.abs(x % 1) === 0.5;
return isTie && rounded % 2 !== 0 ? rounded - 1 : rounded;
}
console.log(halfEven(2.5)); // 2
console.log(halfEven(3.5)); // 4
console.log(halfEven(-2.5)); // -2
console.log(halfEven(-3.5)); // -4
console.log(halfEven(2.6)); // 3
Follow 2.5. Math.round gives 3, it's a tie and 3 is odd, so we return 2. For 3.5, Math.round gives 4, which is already even, so it stays.
Why does subtracting one always work? Math.round sends a tie upwards, so the even neighbor is always the one just below. For -3.5, Math.round gives -3, which is odd, and one below is -4. For a negative odd number, rounded % 2 is -1, which is why the check says !== 0 and not === 1.
Step 4: measure the drift
Take eight ties, as if they were eight interest credits in half-kobo. Their exact total is 32. Round each one, then add them up:
const halfUp = (x) => (x < 0 ? -Math.round(-x) : Math.round(x));
function halfEven(x) {
const rounded = Math.round(x);
const isTie = Math.abs(x % 1) === 0.5;
return isTie && rounded % 2 !== 0 ? rounded - 1 : rounded;
}
const HALVES = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5];
const sum = (list) => list.reduce((a, b) => a + b, 0);
console.log(sum(HALVES)); // 32
console.log(sum(HALVES.map(halfUp))); // 36
console.log(sum(HALVES.map(halfEven))); // 32
console.log(HALVES.map(halfEven)); // [ 0, 2, 2, 4, 4, 6, 6, 8 ]
Half-up adds half a kobo for every row, so eight rows gain four kobo. That's the drift, and it grows with every row. Half-even sends half the ties down and half up, so they cancel and the total matches. That balance is why accounting work often asks for it. The cost is that a single row can surprise someone: 2.5 becoming 2 looks wrong if you don't know the rule.
Step 5: two traps that come before rounding
The first trap is negative zero. JavaScript has a -0 as well as a 0, and Math.round(-0.5) gives -0:
console.log(Object.is(Math.round(-0.5), -0)); // true
console.log(Math.round(-0.5) === 0); // true
console.log(1.005 * 100); // 100.49999999999999
console.log(2.675 * 100); // 267.5
=== treats -0 and 0 as equal, so it hides. Only Object.is tells them apart.
The second trap is a tie that was never a tie. Computers store decimals in binary, and most decimals can't be stored exactly. 1.005 * 100 should be 100.5, a tie, but it comes out a tiny bit under, so both rules round it down to 100 without ever seeing a tie. 2.675 * 100 happens to land on exactly 267.5. A rounding rule only decides what to do with a real tie. Keeping money as whole kobo is what keeps the ties real.
The full solution
The answer panel has halfUp and halfEven, rounds the eight halves both ways, and prints the totals next to Math.round on 2.5 and -2.5. The checks cover symmetry, the even results, the drift, numbers that aren't ties, negative zero and the stored-decimal traps. Press Run to see the output.
// Symmetric: -2.5 goes to -3, the mirror of 2.5 going to 3.
const halfUp = (x) => (x < 0 ? -Math.round(-x) : Math.round(x));
// Half to even, the rule most accounting standards ask for.
function halfEven(x) {
const rounded = Math.round(x);
const isTie = Math.abs(x % 1) === 0.5;
return isTie && rounded % 2 !== 0 ? rounded - 1 : rounded;
}
// Eight half-kobo interest credits. Their exact total is a whole number.
const HALVES = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5];
const sum = (list) => list.reduce((a, b) => a + b, 0);
const exact = sum(HALVES);
const drifted = sum(HALVES.map(halfUp));
const balanced = sum(HALVES.map(halfEven));
console.log('exact', exact, '/ half up', drifted, '/ half even', balanced);
console.log('Math.round(2.5) =', Math.round(2.5), 'but Math.round(-2.5) =', Math.round(-2.5));
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('the built-in sends both halves towards positive infinity', [Math.round(2.5), Math.round(-2.5)], [3, -2]);
test('symmetric half-up mirrors instead', [halfUp(2.5), halfUp(-2.5)], [3, -3]);
test('half to even moves ties to the nearest even number', HALVES.map(halfEven), [0, 2, 2, 4, 4, 6, 6, 8]);
test('so half-up gains four kobo over eight credits and half-even gains nothing', [exact, drifted, balanced], [32, 36, 32]);
test('and half to even is symmetric too', [halfEven(-2.5), halfEven(-3.5)], [-2, -4]);
test('anything that is not a tie is untouched by either rule', [halfUp(2.4), halfEven(2.4), halfUp(2.6), halfEven(2.6)], [2, 2, 3, 3]);
test('Math.round(-0.5) is negative zero, which hides behind a comparison with 0', [Object.is(Math.round(-0.5), -0), Math.round(-0.5) === 0], [true, true]);
test('a tie the float cannot hold never reaches either rule', [1.005 * 100, halfUp(1.005 * 100), halfEven(1.005 * 100)], [100.49999999999999, 100, 100]);
test('and scaling by 100 disagrees with toFixed about the very same number', [2.675 * 100, halfUp(2.675 * 100), (2.675).toFixed(2)], [267.5, 268, '2.67']);
Math.round is documented as rounding a tie towards positive infinity, not away from zero. For positive money that is the half-up everyone expects; for refunds and reversals it is not, and a column containing both drifts in one direction. The fix is one line — round the magnitude and reattach the sign.
Half-to-even exists because half-up is biased. Over the eight halves above it gains four kobo out of thirty-two, and that bias is systematic: every tie moves the same way, so a million rounded interest credits leave a real hole in the ledger. Sending ties to the nearest even number splits them evenly and the totals come out level, which is why it is the default in most financial standards and in Intl.NumberFormat's more careful cousins. The trade-off is that it surprises people reading a single row.
The last three assertions are the reminders. Math.round(-0.5) is -0, which prints as 0 and compares === 0, so it slides through every check except Object.is — then shows up as -0 in a JSON payload or as -Infinity after a division.
And a rounding rule can only act on a tie that survives being stored. 1.005 * 100 is 100.49999999999999, so both rules round it down and the tie is never considered; 2.675 * 100 lands on exactly 267.5 and rounds up to 268, while (2.675).toFixed(2) — working from the stored value, which is a hair under — says '2.67'. Two defensible routes to the same rounding, two different answers, on a number a person typed as three decimal places. Rounding rules decide what to do with a tie. Only integer kobo decides whether the tie is real.
Common mistakes
- Assuming
Math.roundmirrors negatives.Math.round(-2.5)is -2, not -3. Round the size and put the sign back. - Checking
x % 1 === 0.5withoutMath.abs. For a negative tie the remainder is -0.5, so the check misses it. - Expecting a typed decimal to stay a tie.
1.005 * 100isn't 100.5, so no rounding rule will treat it as a half.
Try it yourself
- Run
halfUpandhalfEvenon the negative halves[-0.5, -1.5, -2.5, -3.5]. Do their sums mirror the positive ones? - Write
halfDown, which sends every tie towards zero: 2.5 becomes 2 and -2.5 becomes -2. - Use
halfEvento round[0.5, 1.5, 2.5, 3.5]and count how many went up and how many went down.