1

Please how to round to the nearest decimal tenth? Example : 0.56 => 0.5; 2.78 => 2.8

nullptr
  • 3,701
  • 2
  • 16
  • 40
Mohamed Zahour
  • 338
  • 2
  • 15

1 Answers1

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