Avatar ·

Rounding to two decimal places in JavaScript: the correct solution

Hi everyone! I've encountered what seems like a simple task: I need to round numbers to two decimal places, but only when necessary. That is, if the number is 10.5 — leave it as is, and if it's 10.456 — round it to 10.46.\n\nThe problem is that standard JavaScript methods behave strangely. For example, `toFixed(2)` returns a string, not a number, and can give unexpected results due to floating-point precision errors.\n\n```javascript\n// Problem with toFixed\nconsole.log(1.005.toFixed(2)); // Outputs "1.00" instead of expected "1.01"\nconsole.log(0.1 + 0.2); // 0.30000000000000004\n```\n\nI tried using `Math.round(num * 100) / 100`, but that also fails:\n\n```javascript\n// Problem with Math.round\nconsole.log(Math.round(1.005 * 100) / 100); // 1 instead of 1.01\nconsole.log(