Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Round to the Nearest Tenth?

Given any number of the sort 78.689 or 1.12 for instance, what I'm looking for is to programmatically round the number to the nearest tenth place after the decimal.

I'm trying to do this in an environment where there is a math.floor() function that rounds to the lowest whole number, and as far as I can tell from documentation there's nothing like PHP's round() function.

like image 463
Splashsky Avatar asked Jan 08 '17 14:01

Splashsky


People also ask

What is 5.6 rounded to the nearest tenth?

Rounded to the nearest tenth 5.6 remains 5.6. Since there are no digits in the hundredth place following the 6 in the tenth place we cannot round 5.6 to the nearest tenth.


1 Answers

There's simple snippet at: http://lua-users.org/wiki/SimpleRound

function round(num, numDecimalPlaces)
  local mult = 10^(numDecimalPlaces or 0)
  return math.floor(num * mult + 0.5) / mult
end

It will misbehave when numDecimalPlaces is negative, but there's more examples on that page.

like image 97
Vlad Avatar answered Oct 03 '22 07:10

Vlad