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.
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.
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));1
1.00
1.01
100.49999999999999
2.67 -2 -1The 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.