New: Nitro Boost our Discord server and receive full donation perks here on the website! Join the Scripting Helpers Discord Server to learn more! You can also Support on Patreon as always.
Still have questions? Join our Discord server and get real time help.
Log in to vote

math.round ?

Asked by 5 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
Answered by
adark 5391 Badge of Merit Moderation Voter Community Moderator
5 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))

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

Alright thank you very much! Hydrablox 0 — 5y
You may have noticed the code doesn't work. I updated the code in my answer to fix the bug. adark 5391 — 5y
Log in to vote
Answered by
RedCombee 585 Moderation Voter
5 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