Why do people add 0.5 to the value they want to round down, for example math.floor(mouse.Position.Z + 0.5). What does this do?
math.floor returns the largest integer smaller than or equal to the number passed as an argument. Adding 0.5 guarantees that if the number is like 5.5 it will return 6 instead of 5.
-- Documentation: int math.floor ( number x ) math.floor(5.5) -- return 5 math.floor(5.5 + 0.5) -- return 6
The +.5 helps to round it to the nearest whole number.
For argument’s sake, let’s say we want to round 9.2 to the nearest integer. We can add 0.5 to it, which will give 9.7. When we use math.floor on it, which will round down, we will get 9. Now, say we want to round 9.9 to the nearest integer, we will add 0.5 to it, which will give 10.4, when we use math.floor on it, it’ll return 10
Math.ceil rounds up right? Why don’t devs just use math.ceil?
In school, we generally learn about rounding as rounding to the nearest whole number. Generally in programming libraries, we have functions to floor and ceil, which essentially round down and round up. If you want to round to the nearest integer, you can add .5 to the number before flooring it, or subtract .5 from the number before ceiling it.
Is there any benefit in doing math.ceil(numb) over math.floor(num + 0.5)?
I wouldn’t see the need to use math.ceil, it’s the same as math.floor, but rounds up to the nearest integer larger than or equal to the argument.
print(math.ceil(10.4)) -- 11 print(math.ceil(10.7)) -- 11
Of course, it can be used instead of math.floor, by subtracting 0.5:
print(math.ceil(10.7 - 0.5)) -- 11 print(math.ceil(10.4 - 0.5)) -- 10
There is no added benefit or advantage anyways
Okay that makes sense thank you.
It all matters on what your desired result is. Using just floor will round down and ceil will round up.
Though, ceil(num-.5) is the same as floor(num+.5)
Both of these act as classical rounding (to the nearest integer.)
Why not just use math.round() instead of math.floor() + 0.5 or math.ceil() - 0.5?
Not sure why are you necroposting a topic that was posted six months before
math.round was added, the date this was posted is Feb 2020 and
math.round was introduced in Aug 2020.
math.round is not recommended for geometric snapping.
As many people have mentioned it is so it rounds. Personally I never use math.floor for rounding because it only rounds down, so just use math.round to round up or down (and I’m pretty sure math.ceil is to round up)
Alright, although I didn’t know there was a post about math.round() not being helpful in this scenario.