Avatar ·

Rounding numbers to two decimal places in JavaScript: how to do it correctly?

Hi everyone! I'm a beginner in JavaScript and I've encountered a problem with rounding numbers. I need to display prices in an online store cart, and I want them to always show at most two decimal places. But if the number is an integer (for example, 10), then just show "10" without decimal places.\n\nI tried using `toFixed(2)`, but it always adds zeros: `(10).toFixed(2)` returns `"10.00"`, but I need `"10"`. I tried `Math.round(num * 100) / 100` – it works, but sometimes gives strange results due to floating point precision issues. For example, `Math.round(1.005 * 100) / 100` returns `1` instead of `1.01`, as I expected.\n\nPlease advise how to correctly round a number to two decimal places, but without showing extra zeros when they are not needed? I need a reliable solution.