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

How do you round a decimal value to the nearest whole number?

Asked by 8 years ago

It's a pretty simple question that doesn't require much explanation but this problem I'm having is annoying. So how do you change a decimal number like 123.343 and round it to the nearest whole number? I'm not the best at math. Any help?

2 answers

Log in to vote
5
Answered by
XAXA 1569 Moderation Voter
8 years ago

An elegant solution would be to add 0.5 and round it down.

function round(n)
    return math.floor(n + 0.5)
end

There are several ways of rounding negative numbers. See this page for some more info. This implementation rounds -1.5 to -1, not -2.

1
Thanks for the help! User#11440 120 — 8y
Ad
Log in to vote
1
Answered by
Acheo 230 Moderation Voter
8 years ago
print(math.floor(123.343))

math.floor(NUMBER HERE) allows the decimal to go to the nearest whole number.

1
The nearest whole number to 0.9 is 1, not 0. XAXA 1569 — 8y

Answer this question