Emmanuel Akinfulubi

JavaScriptBasic

Why toFixed(2) rounds 1.005 wrong in JavaScript

Advanced · 4 min read

toFixed(2) is the first thing most people reach for to show a price with two decimals. Then someone types 1.005, expects '1.01', and gets '1.00'. It looks like a bug in JavaScript. It isn't: toFixed is rounding correctly. The number it was given is not the number that was typed.

In this tutorial you will find out why, look at the other surprises toFixed has (it returns text, it handles negative halves its own way, it gives up on huge numbers), and learn one way to nudge it into the answer a person expects. You need to know numbers, strings and for...of loops.

How JavaScript stores a decimal

Computers store numbers in binary, using only 0s and 1s. Whole numbers fit perfectly. Most decimals don't, in the same way that 1/3 can't be written exactly in decimal: 0.3333... goes on for ever. So JavaScript stores the closest number it can, which is usually a tiny bit above or below.

You normally never see this, because JavaScript prints the shortest decimal that leads back to the stored value. Ask for more digits and the real value appears:

JavaScript

console.log(0.1);              // 0.1
console.log(0.1.toFixed(20));  // 0.10000000000000000555

What toFixed does

n.toFixed(d) rounds n to d decimal places and gives back a string, which is text:

JavaScript

console.log((3.14159).toFixed(2)); // 3.14
console.log((3).toFixed(2));       // 3.00
console.log((3).toFixed(0));       // 3

It pads with zeros as well as rounding, which is why it's popular for prices. With 0 places it leaves out the decimal point entirely.

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

146 toFixed does not round the number you typed

hard

(1.005).toFixed(2) gives '1.00', not '1.01'. Show why, find the other things toFixed does that surprise people — its return type, its behaviour on negative halves, what it does to very large numbers — and show one way to nudge it into agreeing.

Stuck? Three hints, smallest first
  1. 1. Print the number to twenty decimal places and read what is actually stored.
  2. 2. toFixed returns a string, which changes what + means.
  3. 3. The stored value is a hair below the half, so no rounding rule can round it up.

Step 1: see the surprise

Start with three amounts that all look like they should round up:

Step 1

for (const n of [1.005, 2.675, 8.575]) {
  console.log(n, '->', n.toFixed(2));
}
// 1.005 -> 1.00
// 2.675 -> 2.67
// 8.575 -> 8.57

All three end in 5 at the third decimal place, and all three round down.

Step 2: read what is really stored

Ask toFixed for twenty places to see what the computer is actually holding:

Step 2

for (const n of [1.005, 2.675, 8.575]) {
  console.log(n, 'is stored as', n.toFixed(20));
}
// 1.005 is stored as 1.00499999999999989342
// 2.675 is stored as 2.67499999999999982236
// 8.575 is stored as 8.57499999999999928946

There's the answer. The stored 1.005 is a hair below 1.005. Rounding it to two places correctly gives 1.00, because it really is closer to 1.00 than to 1.01. It's not a tie at all, so no rounding rule could send it up.

Step 3: scaling doesn't wash the error out

A common idea is to multiply by 100, round, and divide again. The error comes along for the ride:

Step 3

console.log(1.005 * 100);             // 100.49999999999999
console.log(Math.round(1.005 * 100)); // 100

Math.round sees 100.49999999999999, which is below the half, and rounds down. Same answer, same reason.

Step 4: the result is text

This one bites in checkout code. Because toFixed returns a string, + joins instead of adding:

Step 4

const price = (10).toFixed(2);
console.log(typeof price);      // string
console.log(price + 1);         // 10.001
console.log(Number(price) + 1); // 11

'10.00' + 1 sticks the 1 on the end and gives the text '10.001'. Do the maths on numbers, and call toFixed last, only to display the result.

Step 5: halves and huge numbers

When a half can be stored exactly, like 0.5 or 2.5, toFixed rounds it away from zero. That differs from Math.round for negatives:

Step 5

console.log((2.5).toFixed(0));   // 3
console.log((-2.5).toFixed(0));  // -3
console.log(Math.round(-2.5));   // -2
console.log((-0.5).toFixed(0));  // -1
console.log(String(Math.round(-0.5))); // 0
console.log((1e21).toFixed(2));  // 1e+21

toFixed sends -2.5 to -3, while Math.round sends it to -2. In the same way, (-0.5).toFixed(0) is '-1', while Math.round(-0.5) is negative zero, which turns into the text '0'. Mixing the two in one report gives different answers for the same refund.

The last line shows that from 1e21 (a 1 followed by 21 zeros) upwards, toFixed gives up on fixed decimals and returns exponential notation, '1e+21'.

Step 6: the nudge

If you inherit code that keeps money as decimals in naira, there's a patch. toPrecision(12) rewrites a number using only 12 significant digits (digits counted from the first one that isn't zero). The error in 100.49999999999999 sits much further along than that, so it gets rounded away:

Step 6

console.log((1.005 * 100).toPrecision(12)); // 100.500000000
const kobo = (naira) => Math.round(Number((naira * 100).toPrecision(12)));
console.log(kobo(1.005)); // 101
console.log(kobo(2.675)); // 268
console.log(kobo(0.145)); // 15

Number(...) turns the string back into a number, which is now exactly 100.5, and Math.round takes it up to 101 kobo. That's the answer a person expects.

Treat this as a patch, not a cure. It moves the place where the error shows up rather than removing it. The real fix is to store money as a whole number of kobo from the start and only format it at the very end.

The full solution

The answer panel prints each amount next to what is stored, then compares the nudged and plain kobo values. The checks cover the three round-downs, the stored digits, scaling, negative halves, the string result, padding, 1e21 and the nudge. Press Run to see the output.

The answer

// Three amounts a person would type, and what toFixed makes of them.
for (const n of [1.005, 2.675, 8.575]) {
  console.log(n, '-> toFixed(2) ->', n.toFixed(2), '   stored as', n.toFixed(20));
}

// The nudge: re-read the scaled number at 12 significant digits, which throws
// away the error, then round the integer.
const kobo = (naira) => Math.round(Number((naira * 100).toPrecision(12)));
console.log('1.005 as kobo, nudged:', kobo(1.005));
console.log('1.005 as kobo, plain: ', Math.round(1.005 * 100));

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('three amounts that all round down when you expect up', [(1.005).toFixed(2), (2.675).toFixed(2), (8.575).toFixed(2)], ['1.00', '2.67', '8.57']);
test('because 1.005 is not stored as 1.005', (1.005).toFixed(20), '1.00499999999999989342');
test('and the error survives scaling, so plain rounding gets it wrong too', [1.005 * 1000, Math.round(1.005 * 100)], [1004.9999999999999, 100]);
test('a half that IS representable rounds away from zero, both signs', [(0.5).toFixed(0), (1.5).toFixed(0), (2.5).toFixed(0), (-2.5).toFixed(0)], ['1', '2', '3', '-3']);
test('which is not what Math.round does with negatives', [String(Math.round(-2.5)), String(Math.round(-0.5)), (-0.5).toFixed(0)], ['-2', '0', '-1']);
test('the result is a string, so + concatenates instead of adding', [typeof (10).toFixed(2), (10).toFixed(2) + 1], ['string', '10.001']);
test('it pads as well as rounds, and zero places drops the point', [(3).toFixed(2), (3).toFixed(0)], ['3.00', '3']);
test('past 1e21 it gives up and returns exponential notation', (1e21).toFixed(2), '1e+21');
test('re-reading at 12 significant digits first does round the way a person expects', [kobo(1.005), kobo(2.675), kobo(0.145)], [101, 268, 15]);

The second assertion is the whole explanation. Typing 1.005 does not store 1.005; the nearest double is 1.00499999999999989342, which is genuinely below the halfway point, so toFixed is rounding correctly and the input was already wrong. No rounding mode fixes this, because there is nothing to decide — it is not a tie.

Everything else is a separate surprise worth knowing. toFixed returns a string, so total.toFixed(2) + shipping concatenates and you ship '10.001' to the customer. It rounds halves away from zero, unlike Math.round, so the two disagree on every negative half. And past 1021 it abandons fixed notation entirely and hands back '1e+21', which no currency field wants.

The toPrecision(12) nudge works by re-reading the scaled number with fewer significant digits than the error hides in, so 100.49999999999999 becomes 100.5 and rounds up. Use it if you inherit float money and cannot change the storage. Understand that it is a patch: it moves the boundary where the problem appears rather than removing it, and the actual fix is the one from exercise 63 — hold money as an integer number of kobo, and format only at the edge.

Common mistakes

  • Adding to the result of toFixed. It's a string, so + joins. Do the maths first and format last.
  • Looking for a different rounding mode. 1.005 isn't stored as a tie, so every rule rounds it down.
  • Treating the nudge as storage. It patches the display. Store money as whole kobo instead.

Try it yourself

  1. Print (0.145).toFixed(20) and predict whether (0.145).toFixed(2) rounds up or down before you run it.
  2. Write formatNaira(kobo) that takes whole kobo and returns a string like '1.01' without ever calling toFixed on a decimal.
  3. Find a number with three decimals where toFixed(2) does round up the way you'd expect. Check its stored value with toFixed(20).

Keep practising

Newsletter

New writing, when it lands.

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