I'm using percentage on one of my tasks... But there's something very annoying...
I get long decimals numbers...
I would like to truncate...
Could someone help me?
Kenetec's answer is different from the standard definition of "rounding."
round(0.5) is considered to be
0, but Kenetec's will return 0 because it uses
> 0.5 instead of
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).
To round your number, you can make use of the
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
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