Please how to round to the nearest decimal tenth? Example : 0.56 => 0.5; 2.78 => 2.8
Asked
Active
Viewed 106 times
1
-
1You can use `num.toFixed(1)`, although why does `0.56` get rounded to `0.5`? – Spectric Aug 21 '22 at 16:26
-
1No, output is 0.6 – Mohamed Zahour Aug 21 '22 at 16:29
-
1It says `0.56 = > 0.5` in your post. – Spectric Aug 21 '22 at 16:29
1 Answers
4
Multiply by 10, then round then divide back by 10:
const round = (num) => Math.round(num * 10)/10
console.log(round(0.56))
console.log(round(2.78))
Then using the same logic, you can write a general rounding function:
const round = (num, decimal) => Math.round(num * 10**decimal)/10**decimal
console.log(round(5.142533564, 4))
console.log(round(62.5236, 2))

Brother58697
- 2,290
- 2
- 4
- 12
-
1
-
0.56 rounds up to 0.6. If you want it to only round down, replace `Math.round()` in my solution with `Math.floor()` – Brother58697 Aug 21 '22 at 16:47