Skip to content
jshacks.dev
Fundamentals

Round to N decimal places

Round to N decimal places, and see why Math.round(1.005 * 100) / 100 gives 1 and toFixed gives the string 1.00, plus a fix with exponent notation. Node.js 18.

1 min read
Summarize in AI

Math.round(1.005 * 100) / 100 should be 1.01, and it is 1, because 1.005 is not exactly 1.005. The output is from Node.js 24, and there are three ways to deal with it.

JavaScript
console.log(Math.round(1.005 * 100) / 100);
console.log((1.005).toFixed(2));
console.log(Number(Math.round(1.005 + 'e2') + 'e-2'));
console.log(1.005 * 100);
console.log(Number((2.675).toFixed(2)), (-1.5).toFixed(0), Math.round(-1.5));
Text
1
1.00
1.01
100.49999999999999
2.67 -2 -1

The double nearest to 1.005 is slightly below it, so 1.005 * 100 is 100.49999999999999, as the fourth line shows, and rounding that gives 100. toFixed(2) has the same problem, so (1.005).toFixed(2) is '1.00', and it returns a string. The exponent trick avoids the multiplication: Math.round(1.005 + 'e2') reads the text 1.005e2, which parses to exactly 100.5, and + 'e-2' moves the point back, giving 1.01. The last line shows two more rules about halves: (2.675).toFixed(2) is 2.67, because that number is also stored slightly below, and (-1.5).toFixed(0) is -2 while Math.round(-1.5) is -1, since the two round halves differently. See the specification for Number.prototype.toFixed.

The trick breaks for numbers that already print in exponent form, so 1e-7 + 'e2' is NaN. For money, store integer cents and round once when you divide. Intl.NumberFormat with maximumFractionDigits: 2 printed 1.01 for the same input when we tried it, and it is the better choice for display.

Taggednode 24
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.