|
| 27 Jan 2012 11:03 PM |
| How do I round a value to the nearest integer? (in a script) |
|
|
| Report Abuse |
|
|
|
| 27 Jan 2012 11:08 PM |
| I'm not sure if there's a method, but I would try using if v >= 5 then and if v < 5 then. |
|
|
| Report Abuse |
|
|
|
| 27 Jan 2012 11:11 PM |
num1 = 2.5; num1 = math.ceil(num1);
math.ceil rounds up, math.floor rounds down. You could make a function to detect which, ie:
function round(num) if (math.ceil(num) - num) < (num - math.floor(num)) then return math.ceil(num) elseif (math.ceil(num) - num) > (num - math.floor(num)) then return math.floor(num) else return math.ceil(num) end
round(6.8)
> 7 |
|
|
| Report Abuse |
|
|
|
| 27 Jan 2012 11:11 PM |
local decimal = 5.63 local int = math.floor(decimal+.5) print(int) |
|
|
| Report Abuse |
|
|
|
| 27 Jan 2012 11:12 PM |
Actually, you'd call the function with print(round(6.8)), and then you could do stuff like:
num1 = 6.7; num1 = round(num1); print(num1);
> 7 |
|
|
| Report Abuse |
|
|
|
| 27 Jan 2012 11:18 PM |
if you want to round to a range use this (and no miz i did not test it):
function round(num,range) --range is optional, it will just convert to int if you dont put range in. range = range or 1 return (num+(range/2))-((num+(range/2))%range) end
print(round(364,100))
>400 |
|
|
| Report Abuse |
|
|