Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
Rounding — Gideros Forum

Rounding

HarrisonHarrison Member
edited May 2014 in General questions
In programming, rounding down to the ones place is important.. think hours to minutes, dollars to change.. etc.
I made a exel spreadsheet that did just that-
in psudocode:
x=5.223
y=rounddown(x) (to the nearest ones place)
x=x-y
print(x..":"..y)
(in a perfect world would yield 5:0.22)
but when i attempt to round in lua there is no simple round function unlike exel..
math.floor just takes my number to zero D:
so does this:
 function round(num) 
        if num >= 0 then return math.floor(num+.5) 
        else return math.ceil(num-.5) end
    end
also yields 0
which i got from http://lua-users.org/wiki/SimpleRound
First, why?
Next, what should i be doing?
“ The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time. ” - Tom Cargill

Comments

  • amin13aamin13a Member
    It works for me:
    in main.lua (and no other code):

    function round(num)
    if num >= 0 then return math.floor(num+.5)
    else return math.ceil(num-.5) end
    end
    print(round(2.85))

    Result:
    main.lua is uploading.
    Uploading finished.
    3
  • HubertRonaldHubertRonald Member
    edited May 2014
    Hi @Harrison

    I use the next code:
    local floor = math.floor
    function round(val, decimal)
      if (decimal) then
        return floor( (val * 10^decimal) + 0.5) / (10^decimal)
      else
        return floor(val+0.5)
      end
    end
     
     
    print(math.pi)
    print(round(math.pi))
    print(round(math.pi,4))
     
    --[[
       I get:
       3.1415926535898
       3
       3.1416
    ]]
    In your case I would do the following
    local x = 5.223 -- input
    local y = round(x,2) -- define numbers of decimals
    x = round(x) -- rounddown integer
    y = y - x -- get decimals
    print(table.concat({x,":",y})) -- it's more fast!
     
    --[[
       I get:
       5:0.22
    ]]
    I hope than it can hep you :)>-
  • HarrisonHarrison Member
    edited May 2014
    thanks, that helps a lot. Now i just need to fix the results when something with a decimal over 0.5 is passed (ex. 5.55 results in 6 and -0.45)
    edit:
    fixed by doing this after your second block of code you posted-
     if y < 0 then --checks to see if the rounding code rounded up 
    y = 1 + y --takes the negative y and finds its positive opposite
    x=x-1 --removes 1 from x to make up for upward round
    end
    man this concept is hard to wrap my mind around! :D
    “ The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time. ” - Tom Cargill
Sign In or Register to comment.