2

# How do I round numbers in Lua? [Answered] [closed]

I'm using percentage on one of my tasks... But there's something very annoying...

I get long decimals numbers...

29.86577181281

I would like to truncate...

Could someone help me?

0
Use one of the round functions below like this: round(n / 0.1) * 0.1. This will round to a decimal place you want. For example, 0.01 will round to the nearest hundredth, etc. Tkdriverx 514 — 7y

### Locked by EzraNehemiah_TF2, Tkdriverx, and M39a9am3R

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

3
BlueTaslem 18062
8 years ago

Kenetec's answer is different from the standard definition of "rounding."

Generally, round(0.5) is considered to be 1, not 0, but Kenetec's will return 0 because it uses > 0.5 instead of >= 0.5

Nevertheless, the ternary operation that Kenetec's solution performs is needlessly complicated to implement. The following is a true and useful definition of rounding, which is much simpler:

round(x) = floor(x + 0.5)


If we instead write this as

round(x) = x + 0.5 - (x + 0.5) % 1


we get a 20% speedup over Kenetec's solution (if performance is significant).

2
Thank you for the answer and the performance (:D) FieryEvent 185 — 8y
3

To round your number, you can make use of the math.floor and math.ceil functions.

math.floor will always round down to the next integer, and math.ceil will always round up. There is no built-in function to round "normally", meaning if the decimal is .5 or greater, we go up, and if it is lower, we go down.

However, not to worry! We can create our own function to do just this.

function round(n)
return n % 1 >= 0.5 and math.ceil(n) or math.floor(n)
end


This function makes use of the modulus operator, which gives us the remainder of a division operation. Because we are using 1, it will try to divide the number by 1, and then give us the remainder, which will be the decimal that was with the whole number. Then, we compare it to see if it is greater than 0.5, and if it is, we will use the math.ceil function on it to round up, and if not, the math.floor function to round down. This function makes use of Lua's boolean operators to allow us to create this operation in one line, as opposed to using an if statement.

Have you tried using math.round()? I'm not so familiar with this function, but I know it exists. Look around in the wiki for more information about the math.*() functions.
math.round is not a valid function in the math library. User#11893 186 — 8y