I want to round a number so that it shows only one digit after the decimal point, properly rounded.
I tried multiplying by 10, using Math.round()
, and then dividing by 10, but sometimes it still shows two decimals. What’s the best way to handle javascript round to 1 decimal correctly?
Yeah, your approach is right, multiply by 10, round, then divide by 10:
function roundToOneDecimal(num) {
return Math.round(num * 10) / 10;
}
This gives you a number rounded to one decimal place.
Just remember the result is a number, so when you print it, JavaScript might show more decimals because of how it handles floating-point numbers.
I agree you approach is right @kusha.kpr, however, if you want a string with exactly one decimal place (even if it’s zero), try toFixed(1)
:
const roundedStr = num.toFixed(1);
This returns a string like “2.30” or “1.00”. It rounds properly and always shows one decimal digit. If you want it back as a number, wrap it with parseFloat().
Just an opinion here , sometimes, because of floating-point precision, you might see weird things like 1.999999 rounding oddly.
Using Math.round(num * 10) / 10
is usually fine, but for really accurate decimal math, consider libraries like Decimal.js.
For everyday use, toFixed(1)
is your best friend.