Round a number to 2 decimal places in JavaScript
Beginner · 3 min read
Prices, exam averages and distances are usually shown with two decimal places: 3.14, not 3.14159. JavaScript gives you a quick way to do this, toFixed, and it hides two surprises. It hands back text instead of a number, and it rounds some numbers the "wrong" way.
In this tutorial you will round with toFixed, write roundTo(n, places) that keeps the result as a number, and find out why (1.005).toFixed(2) gives '1.00'. You need to know what a number, a string and a function are.
Rounding to a number of places
Math.round rounds to the nearest whole number. It has no "number of decimal places" option:
console.log(Math.round(3.14159)); // 3
console.log(Math.round(3.5)); // 4
To round to two places, you can move the decimal point, round, and move it back. Multiplying by 100 moves the point two places right, so 3.14159 becomes 314.159. Rounding gives 314. Dividing by 100 gives 3.14.
Text versus number
The difference between 3.14 and '3.14' matters. The first is a number you can do sums with. The second is text, and + joins text instead of adding it:
console.log(3.14 + 1); // 4.140000000000001
console.log('3.14' + 1); // 3.141
The first line shows a tiny decimal error, which is normal for decimals in JavaScript. The second line is the bigger problem: the 1 was stuck on the end.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
51 Round to a given number of decimal places
easyRound a number to two decimal places, then to any number of places. Say what type toFixed hands back.
Stuck? Three hints, smallest first
- 1.
toFixed(2)rounds to two places, but read its return type carefully. - 2. To round and keep a number, multiply by a power of ten,
Math.round, then divide back. - 3. Try
(1.005).toFixed(2)and see whether you get what you expected.
Step 1: round with toFixed
toFixed(2) rounds to two places and pads with zeros if needed:
const money = (n) => n.toFixed(2);
console.log(money(3.14159)); // 3.14
console.log(typeof money(3.14159)); // string
console.log((2.5).toFixed(3)); // 2.500
The brackets around 2.5 stop JavaScript reading the dot as a decimal point. typeof confirms that the result is text. That is what makes toFixed good for showing a price: 2.500 keeps its zeros, which a number never would.
Step 2: the string bug in a total
Because toFixed returns text, math after it goes wrong without any error:
console.log((1.5).toFixed(2) + 1); // 1.501
You wanted 2.5 and got the text 1.501. When you need to calculate again, wrap the result in Number(...), or use the next step instead.
Step 3: round and keep a number
Turn the move-round-move idea into a function. 10 ** places means 10 to the power of places: 100 for two places, 1,000 for three.
const roundTo = (n, places) => {
const factor = 10 ** places;
return Math.round(n * factor) / factor;
};
console.log(roundTo(3.14159, 2)); // 3.14
console.log(roundTo(3.14159, 3)); // 3.142
console.log(typeof roundTo(3.14159, 2)); // number
The result is a real number, so you can keep doing sums with it.
Step 4: the 1.005 surprise
Rounding 1.005 to two places should give 1.01, because the 5 rounds up. Try it:
console.log((1.005).toFixed(2)); // 1.00
console.log((2.675).toFixed(2)); // 2.67
Both round down. This isn't a bug in toFixed. Numbers in JavaScript are stored in binary, and most decimals, like 1.005, can't be stored exactly. The computer keeps the nearest value it can. Ask for 17 places to see what is really stored:
console.log((1.005).toFixed(17)); // 1.00499999999999989
The stored value is a hair below 1.005, so rounding it to two places is correctly 1.00. Your roundTo meets the same stored value. For money, the usual fix is to avoid decimals altogether and count whole kobo or cents instead.
The full solution
The answer panel has money and roundTo, prints both with their types, and shows the 1.005 case and its stored value. The checks also cover 2.675 and the '1.501' string bug. Press Run to see the output.
// toFixed rounds to a fixed width and returns TEXT, not a number.
const money = (n) => n.toFixed(2);
// Rounding and staying numeric: scale up, round, scale back down.
const roundTo = (n, places) => {
const factor = 10 ** places;
return Math.round(n * factor) / factor;
};
console.log('toFixed(2) ->', money(3.14159), 'type', typeof money(3.14159));
console.log('roundTo(,2) ->', roundTo(3.14159, 2), 'type', typeof roundTo(3.14159, 2));
console.log('padded ->', (2.5).toFixed(3));
console.log('1.005 to 2 places ->', (1.005).toFixed(2), '<- not 1.01');
console.log('because it is stored as ', (1.005).toFixed(17));
Output
8 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 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('toFixed hands back a string', typeof (3.14159).toFixed(2), 'string');
test('so it needs converting back', roundTo(3.14159, 2), 3.14);
test('three places', roundTo(3.14159, 3), 3.142);
test('toFixed pads out to the width asked for', (2.5).toFixed(3), '2.500');
test('1.005 rounds DOWN, which looks wrong', (1.005).toFixed(2), '1.00');
test('and so does 2.675', (2.675).toFixed(2), '2.67');
test('the stored value explains it', (1.005).toFixed(17), '1.00499999999999989');
test('a string will not add up', (1.5).toFixed(2) + 1, '1.501');
Two separate lessons. First, toFixed returns a string, so price.toFixed(2) + 1 gives "1.501" rather than 2.5 — the last assertion is the bug as it actually appears, in a total that comes out as gibberish. Wrap it in Number(...) the moment you need arithmetic again.
Second, (1.005).toFixed(2) is "1.00", and that is not a bug in toFixed. The literal 1.005 cannot be stored exactly, so what is actually in the variable is 1.00499999999999989, and rounding that to two places is correctly 1.00. Exercise 63 is the fix for money: keep integers.
Common mistakes
- Doing math on
toFixed's result. It is a string, so+ 1joins instead of adding. Convert withNumber(...)first. - Rounding in the middle of a calculation. Each rounding throws a little away. Keep full numbers while you calculate and round once, when you display.
- Expecting 1.005 to round up. The stored value is slightly below 1.005, so it rounds down.
Try it yourself
- Format a list of prices
[3, 4.5, 10.256]so each shows exactly two decimals. - Use
roundTowith-1places on1234. What happens, and why does10 ** -1explain it? - Store a price of 18.99 as
1899kobo, add three of them, and show the total with two decimals.