(Math Help) How do I round to the nearest 50?

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
User avatar
icekiller8002
Prole
Posts: 35
Joined: Mon Jun 06, 2016 9:28 pm
Location: United States

(Math Help) How do I round to the nearest 50?

Post by icekiller8002 » Fri Jun 14, 2019 7:16 pm

I.E.
23 = 0
27 = 50
56 = 50
79 = 100
122 = 100
143 = 150
178 = 200
994 = 1000

Basically, if the last two digits are closer to 100, then it rounds it to 100. Otherwise, if the last two digits are closer to 50, then it rounds it to 50. Or if the last two digits are closer to zero, then it rounds it to zero.

Code: Select all

function love.draw()
  love.graphics.print("obey")
end

TheHUG
Prole
Posts: 30
Joined: Sun Apr 01, 2018 4:21 pm

Re: (Math Help) How do I round to the nearest 50?

Post by TheHUG » Fri Jun 14, 2019 7:26 pm

first thing that comes to mind is:

Code: Select all

function roundnearest(num, to)
    local rem = num % to
    if rem < (to / 2) then
        return num - rem
    else
        return num - rem + to
    end    
end
(then you call it with '50' as the second argument)
edit: messed it up, need sleep. fixed.

User avatar
raidho36
Party member
Posts: 1766
Joined: Mon Jun 17, 2013 12:00 pm

Re: (Math Help) How do I round to the nearest 50?

Post by raidho36 » Fri Jun 14, 2019 10:38 pm

You can try the following:

Code: Select all

function roundTo ( number, multiple )
  return math.floor ( ( number / multiple ) + 0.5 ) * multiple
end

Post Reply

Who is online

Users browsing this forum: Exabot [Bot], Google [Bot] and 8 guests