Round float number to the closest whole number

Hello developers!
(this isn’t really a tutorial but it is kinda)

I always had trouble with rounding a number to the closest whole number.
A lot of people think there are only math.floor() and math.ceil().

BUT!
Recently, I discovered a “hidden” math function in Roblox, it’s hidden because autocomplete doesn’t shows it up and I can’t find any post about this function.

Here’s how you can use it:
example #1:

print(math.round(0.42)) -- 0
print(math.round(0.9)) -- 1
print(math.round(1.39)) -- 1
print(math.round(3.8)) -- 4

example #2:

local round = math.round
print(round(0.45)) -- 0
print(round(0.5)) -- 1
print(round(1.4)) -- 1
print(round(1.62)) -- 2

I hope you find this useful!
Cya!

6 Likes

And to anyone that wants all of the math functions and properties:

2 Likes

I never noticed that it doesn’t autocomplete, interesting

2 Likes

I thought “round” was a hidden variable lol, didn’t read it properly.

If that was actually the case of a global for it, then I wouldn’t recommend using it as it would be very likely unoptimized.

By the way, you don’t have to localize library functions on Luau for speed, that gets optimized so it’s not needed, it’s only slightly faster on Luau, it’s really only a problem in Lua, + it’s inconvenient and on some code styles it looks ugly;

Anyhow, I recommend you report this to @Bug-Support (if there’s no topic talking about this already).

Roblox-LSP handles this properly :)


I tested average time using math.round and a custom round function as of now they’re the same, probably because it’s a super simple concept to round a number.

local function round(n)
    return math.floor(n + .5)
end

But no I don’t recommend using a custom function for round as it’s better to always use roblox’s function as it can be updated to run better, handle errors properly, etc.

image

This is the amount of seconds in average (ran 3 times and then divided) for 100 runs on trying to round 2.65 not assigning it to any variable, just calling the function.

1 Like