math.round isn't working?

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
jakie
Prole
Posts: 4
Joined: Tue Feb 03, 2015 1:27 am

math.round isn't working?

Post 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
User avatar
Nixola
Inner party member
Posts: 1949
Joined: Tue Dec 06, 2011 7:11 pm
Location: Italy

Re: math.round isn't working?

Post 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
lf = love.filesystem
ls = love.sound
la = love.audio
lp = love.physics
lt = love.thread
li = love.image
lg = love.graphics
User avatar
zorg
Party member
Posts: 3465
Joined: Thu Dec 13, 2012 2:55 pm
Location: Absurdistan, Hungary
Contact:

Re: math.round isn't working?

Post 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.
Me and my stuff :3True Neutral Aspirant. Why, yes, i do indeed enjoy sarcastically correcting others when they make the most blatant of spelling mistakes. No bullying or trolling the innocent tho.
jakie
Prole
Posts: 4
Joined: Tue Feb 03, 2015 1:27 am

Re: math.round isn't working?

Post by jakie »

Thanks. Much appreciated
User avatar
rmcode
Party member
Posts: 454
Joined: Tue Jul 15, 2014 12:04 pm
Location: Germany
Contact:

Re: math.round isn't working?

Post by rmcode »

Code: Select all

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

Who is online

Users browsing this forum: Ahrefs [Bot], Bing [Bot] and 4 guests