Page 1 of 1

math.round isn't working?

Posted: Fri Jun 03, 2016 11:04 pm
by jakie
I want to use math.round in my project, but errors are thrown.
I tested this problem in a new 1 line project with the math module enabled in the config.

Why isn't math.round working for me?

Code: Select all

print(math.round(1.2))
Image

Re: math.round isn't working?

Posted: Fri Jun 03, 2016 11:11 pm
by Nixola
Because math.round doesn't exist. It's a convenience function provided in some frameworks (I think it exists in gmod, for example), but it's not part of the Lua standard library and LÖVE devs don't want to interfere with that. You can easily define it as such:

Code: Select all

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

Re: math.round isn't working?

Posted: Sat Jun 04, 2016 12:27 am
by zorg
Did some research with these things, and the following definitions seemed the fastest in Löve;

Code: Select all

-- math.floor rounds to negative infinity
-- math.ceil rounds to positive infinity
math.trunc = function(n) return n >= 0.0 and n-n% 1 or n-n%-1 end -- rounds towards zero from both infinities
math.round = function(n) return n >= 0.0 and n-n%-1 or n-n% 1 end -- rounds away from zero, towards both infinities
Not to mention the fact that these definitions provide all of the "big 4" rounding functions, though none of them handle the .5 thing specially.

Re: math.round isn't working?

Posted: Sat Jun 04, 2016 1:04 am
by jakie
Thanks. Much appreciated

Re: math.round isn't working?

Posted: Wed Jun 08, 2016 10:47 pm
by rmcode

Code: Select all

math.floor( val + 0.5 )
Works fine in a lot of cases.