How do you round a number to at most two decimal places only when needed in JavaScript?
Use **Math.round((num + Number.EPSILON) * 100) / 100** to round accurately to at most two decimal places as a real Number—automatically dropping trailing .00zeros unlike.toFixed(2)`.
Accurate Decimal Rounding Without Trailing Zeros
function roundMaxTwo(num) {
return Math.round((num + Number.EPSILON) * 100) / 100;
}
console.log(roundMaxTwo(10)); // 10 (no .00)
console.log(roundMaxTwo(10.5)); // 10.5 (no trailing 0)
console.log(roundMaxTwo(10.456)); // 10.46
console.log(roundMaxTwo(1.005)); // 1.01 (Number.EPSILON prevents float drift)
Alternative Using Number() + .toFixed(2)
const clean = Number((12.300).toFixed(2)); // 12.3 '
You must log in or register to comment.
