Emmanuel Akinfulubi

JavaScriptMath

Why toFixed rounds 2.675 down in JavaScript

Intermediate · 4 min read

You show a price with toFixed(2), and 2.675 comes out as "2.67" instead of "2.68". It looks like JavaScript can't round. It can. The problem is that the number you wrote as 2.675 was never quite 2.675.

In this tutorial you will find out what 1.005, 2.675 and 8.575 really are inside the computer, and why toFixed rounds them down. Then you will compare three rounding rules on the halves from -2.5 to 3.5 (toFixed, Math.round and banker's rounding) and see which one keeps a total honest. You need to know arrow functions, map and reduce.

Numbers are stored in binary

JavaScript stores every number as a binary fraction. Most decimals, like 0.1 or 2.675, have no exact binary form, so each one is stored as the nearest value the computer can hold. Usually that value is a hair above or a hair below what you typed. You don't normally see it, because JavaScript prints the shortest decimal that leads back to the same stored value.

Rounding a tie

When a number sits exactly halfway, like 2.5, a rounding rule has to choose. There are three common choices:

  • Half away from zero: 2.5 becomes 3 and -2.5 becomes -3.
  • Half up: always toward the bigger number, so 2.5 becomes 3 but -2.5 becomes -2.
  • Half to even, also called banker's rounding: go to whichever neighbor is even, so 2.5 becomes 2 and 3.5 becomes 4.

Here is the exercise. Try it on your own first if you like, then read on and we will build it together.

87 toFixed rounds the double it was handed

fair

Round 1.005, 2.675 and 8.575 to two places with toFixed and explain the results. Then compare toFixed, Math.round and a hand-written banker's rounding on the halves from -2.5 to 3.5, and show which of the three keeps a sum unchanged.

Stuck? Three hints, smallest first
  1. 1. toPrecision(20) shows what the literal 1.005 really is.
  2. 2. toFixed rounds halves away from zero; Math.round rounds them towards positive infinity.
  3. 3. Banker's rounding sends a tie to whichever neighbour is even.

Step 1: what toFixed returns

Step 1

console.log(typeof (1.5).toFixed(2), (1.5).toFixed(2)); // string 1.50

toFixed returns text, not a number, and it pads with zeros to the number of places you ask for. That is why it is good for display.

Step 2: the surprise

Step 2

console.log((1.005).toFixed(2)); // 1.00
console.log((2.675).toFixed(2), (8.575).toFixed(2)); // 2.67 8.57

All three round down, when you'd expect 1.01, 2.68 and 8.58.

Step 3: look at the real value

toPrecision(20) shows a number to 20 significant digits, so you can see past the short version JavaScript usually prints.

Step 3

console.log((1.005).toPrecision(20)); // 1.0049999999999998934
console.log((2.675).toPrecision(20)); // 2.6749999999999998224

There it is. The stored value for 1.005 is a little below 1.005. To two places, the nearest answer really is 1.00. toFixed rounds correctly; it just rounds the value it was given, and that value was never 1.005. The same goes for 2.675 and 8.575.

No rounding rule can fix this, because the missing bit was lost the moment the number was written into the code.

Step 4: real halves with toFixed

Halves like 0.5 and 2.5 are exact in binary, so here the rounding rule shows.

Step 4

const halves = [0.5, 1.5, 2.5, 3.5, -0.5, -1.5, -2.5];
console.log(halves.map((x) => x.toFixed(0)).join(' ')); // 1 2 3 4 -1 -2 -3

toFixed rounds ties away from zero, the same distance on both sides.

Step 5: Math.round does it differently

Step 5

console.log(halves.map(Math.round).join(' ')); // 1 2 3 4 0 -1 -2
console.log(Object.is(Math.round(-0.5), -0));  // true

Math.round rounds ties up, toward the bigger number. So -1.5 becomes -1 and -2.5 becomes -2. The two built-in rules agree on every positive tie and disagree on every negative one.

Math.round(-0.5) is minus zero, a special value that equals 0 with ===. join turns it into "0", which is why the first line shows 0. Object.is is the comparison that can see the difference.

Step 6: banker's rounding by hand

Step 6

const roundHalfEven = (x) => {
  const down = Math.floor(x);
  const frac = x - down;
  if (frac > 0.5) return down + 1;
  if (frac < 0.5) return down;
  return down % 2 === 0 ? down : down + 1;
};
console.log(halves.map(roundHalfEven).join(' ')); // 0 2 2 4 0 -2 -2

Math.floor gives the whole number below, and frac is the part left over. Above a half, go up. Below a half, go down. On an exact tie, pick whichever of down and down + 1 is even.

Step 7: why accountants use it

Step 7

const add = (a, b) => a + b;
const ties = [0.5, 1.5, 2.5, 3.5];
console.log(ties.reduce(add, 0));                     // 8
console.log(ties.map(Math.round).reduce(add, 0));     // 10
console.log(ties.map(roundHalfEven).reduce(add, 0));  // 8

The real total is 8. Rounding every tie up gives 10: each one adds half a unit, and that bias grows with every row. Banker's rounding sends half the ties up and half down, so the total stays at 8.

Step 8: two edges

Step 8

console.log((1e21).toFixed(2)); // 1e+21
console.log((-0).toFixed(2));   // 0.00

From 1e21 upward, toFixed gives up and returns the number in exponent form. And minus zero loses its sign on the way to text.

The full solution

The answer panel has the halves, roundHalfEven and the sums, and prints the three surprising values, their real digits, all three rounding rules and the two edges. Press Run to see the output.

The answer

const add = (a, b) => a + b;
const halves = [0.5, 1.5, 2.5, 3.5, -0.5, -1.5, -2.5];

// Round half to even, the accounting default.
const roundHalfEven = (x) => {
  const down = Math.floor(x);
  const frac = x - down;
  if (frac > 0.5) return down + 1;
  if (frac < 0.5) return down;
  return down % 2 === 0 ? down : down + 1;
};

console.log('typeof toFixed     :', typeof (1.5).toFixed(2), (1.5).toFixed(2));
console.log('1.005 to 2 places  :', (1.005).toFixed(2), 'because it is', (1.005).toPrecision(20));
console.log('2.675 and 8.575    :', (2.675).toFixed(2), (8.575).toFixed(2));
console.log('real halves        :', halves.map((x) => x.toFixed(0)));
console.log('Math.round         :', halves.map(Math.round));
console.log('half to even       :', halves.map(roundHalfEven));
console.log('sums               :', [0.5, 1.5, 2.5, 3.5].map(Math.round).reduce(add, 0), [0.5, 1.5, 2.5, 3.5].map(roundHalfEven).reduce(add, 0), 0.5 + 1.5 + 2.5 + 3.5);
console.log('minus zero, 1e21   :', (-0).toFixed(2), (1e21).toFixed(2));

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.

9 checks

test('toFixed returns a string, and pads to the width you asked for', [typeof (1.5).toFixed(2), (1.5).toFixed(2)], ['string', '1.50']);
test('1.005 to two places is 1.00, because the stored value is below the half', [(1.005).toFixed(2), (1.005).toPrecision(20)], ['1.00', '1.0049999999999998934']);
test('2.675 and 8.575 are stored low in the same way, so both round down', [(2.675).toFixed(2), (8.575).toFixed(2)], ['2.67', '8.57']);
test('where the half is a real half, toFixed rounds away from zero on both sides', halves.map((x) => x.toFixed(0)), ['1', '2', '3', '4', '-1', '-2', '-3']);
test('Math.round rounds ties up instead, which makes -0.5 into minus zero', [Math.round(0.5), Math.round(2.5), Object.is(Math.round(-0.5), -0), Math.round(-1.5), Math.round(-2.5)], [1, 3, true, -1, -2]);
test('banker rounding sends every tie to the even neighbour, in both signs', halves.map(roundHalfEven), [0, 2, 2, 4, 0, -2, -2]);
test('and that is why accounting uses it: the total survives rounding', [[0.5, 1.5, 2.5, 3.5].map(Math.round).reduce(add, 0), [0.5, 1.5, 2.5, 3.5].map(roundHalfEven).reduce(add, 0), 0.5 + 1.5 + 2.5 + 3.5], [10, 8, 8]);
test('above 1e21 toFixed gives up and hands back exponential notation', (1e21).toFixed(2), '1e+21');
test('and minus zero loses its sign on the way to a string', [(-0).toFixed(2), Object.is(-0, 0)], ['0.00', false]);

The specification for toFixed says: pick the integer n for which n / 10 ** f is closest to the value, and on a tie pick the larger magnitude. That is round-half-away-from-zero, so (0.5).toFixed(0) is '1' and (-0.5).toFixed(0) is '-1'. Math.round is different: it rounds ties towards positive infinity, so Math.round(-0.5) is -0 and Math.round(-1.5) is -1. Two rounding rules in the same language, disagreeing on every negative tie.

(1.005).toFixed(2) returning '1.00' is not a bug in either rule. The literal 1.005 is stored as 1.0049999999999998934, which is genuinely below the halfway point, so rounding down is correct. toFixed rounds the double it was handed, and that double was never 1.005. The same applies to 2.675 and 8.575. No rounding mode can fix this, because the information was lost when the literal was parsed.

Banker's rounding exists for the last assertion. Rounding 0.5, 1.5, 2.5 and 3.5 up gives 10 where the true total is 8: a consistent upward bias of half a unit per tie, which on a ledger of a million rows is real money. Sending ties to the even neighbour cancels the bias and the total comes out at 8. If you are rounding naira, round to even, or better, hold kobo as integers and never round at all.

Common mistakes

  • Blaming toFixed for 2.675. The stored number is below 2.675, so 2.67 is the correct rounding. For money, store whole kobo or cents instead.
  • Assuming Math.round and toFixed agree. They differ on every negative tie: -2.5 gives -2 and '-3'.
  • Doing math on the result of toFixed. It is a string, so (1.5).toFixed(2) + 1 gives "1.501".

Try it yourself

  1. Use toPrecision(20) to check whether 1.255 is stored above or below 1.255. Predict (1.255).toFixed(2) before running it.
  2. Write roundHalfEvenTo(x, places) that rounds to a number of decimal places. Test it on values that are exact in binary, like 0.125.
  3. Round 0.5, 1.5, ... up to 9.5 with both Math.round and roundHalfEven, and compare the two totals with the real one.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.