Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

math.round ?

Asked by 10 years ago

I want to round up a number, for example: 4.9855 till 3 decimals, is there way to do that ?

2 answers

Log in to vote
3
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
10 years ago

As neither of the other posts actually rounded the number, only truncated, here's your answer.

The way to round any number to the closest whole number is as such:

local number = 12.513
local rounded = math.floor(number + .5)
print(rounded) -- 13

Now, that might not seem useful, but it's actually the solution you want! All you have to do to round to something other than a whole number is to multiply by powers of ten:

local degree = 3 --Positive is decimal places to the right, negative is to the left. 0 is whole number
local number = 23.15174246
local rounded = math.floor((number * 10^degree) + .5)*10^(-degree)
print(rounded) -- 23.152

Now, this isn't perfect, but the only exception is this: when numberis negative, .5 exactly (on the degree given) rounds up to the number closer to 0, not down as is expected.

In order to fix this, we have to 'catch' whether the number is negative or positive, then round its absolute value:

local degree = 0
local number = -12.5 -- -13 is expected, as -.5 is closer to -1 than to 0
local neg = number < 0 and -1 or 1
local rounded = neg*math.abs(math.floor((number * 10^degree) + .5)*10^(-degree))
print(rounded) -- -13

Now, this is a very useful bit of code, but you may not want to have to paste all that code all over the place, so here's it in function form:

function roundNum(number, degree)
    if not number then error("Cannot round nil") end
    if not degree then degree = 0 end
    return (number < 0 and -1 or 1)*math.abs(math.floor((number * 10^degree) + .5)*10^(-degree))
end

EDIT: Just noticed I cancelled the power-of-ten multiplication before rounding the number, fixed it in all that applies to.

0
Alright thank you very much! Hydrablox 0 — 10y
0
You may have noticed the code doesn't work. I updated the code in my answer to fix the bug. adark 5487 — 10y
Ad
Log in to vote
-2
Answered by
RedCombee 585 Moderation Voter
10 years ago

To round, the easiest way is to take the variable with the number you have.

number = string.sub(number, 1,5)

This makes it cut off at the first five in your example. If you need any more than that let me know.

Answer this question