How to round to the nearest tenth?

Given any sort number 78.689 or 1.12, for example, I want the program code to round the number to the nearest tenth place after the decimal number.

I am trying to do this in an environment where there is a function math.floor()that is rounded to the lowest integer, and as far as I can tell from the documentation, there is nothing like a PHP function round().

+4
source share
4 answers

There is a simple snippet here: 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

This will not be true if numDecimalPlaces is negative, but there are more examples on this page.

+7
source

, ... , printf... - .

value = 8.9756354
print(string.format("%2.1f", value))
-- output: 9.0
+3

Given that this is roblox, it would be easier to make this global variable instead of creating a single module or creating your own gloo.

_G.round = function(x, factor) 
    local factor = (factor) and (10 ^ factor) or 0
    return math.floor((x + 0.5) * factor) / factor
end
+1
source

In my case, I was just trying to make a string representation of this number ... however, I believe that this solution may be useful for others as well.

string.sub(tostring(percent * 100), 1, 4)

to return it to a numerical representation, you can simply call tonumber()on the resulting number.

0
source

Source: https://habr.com/ru/post/1666148/


All Articles