In Lua, how can I tell if a number divides evenly into another number?

15,800

Compare the remainder of the division to zero, like this:

12 % 6 == 0

18 % 6 == 0

20 % 6 ~= 0

The modulus operator (%) returns the remainder of division. For 12 and 6 it is 0, but for 20 and 6 it is 2.

The formula it uses is: a % b == a - math.floor(a/b)*b

Share:
15,800
Scott Phillips
Author by

Scott Phillips

Updated on June 22, 2022

Comments

  • Scott Phillips
    Scott Phillips almost 2 years

    In Lua, how can I tell if a number divides evenly into another number? i.e with no remainder? I'm just looking for a boolean true or false.

    12/6 = 2 (true)
    18/6 = 3 (true)
    20/6 = 3.(3) (false)
    
  • etandel
    etandel over 12 years
    The cool thing about % is that it works on real numbers as well
  • BMitch
    BMitch about 12 years
    For comparisons to 0, the modulus operator appears to work fine. No need to make an extra function call.
  • Eric
    Eric over 11 years
    Whether -13 % 6 == 5 is incorrect a matter of opinion. This is often the behaviour you want.