Check if an integer is divisible by another integer (Swift)

Tom Coomer picture Tom Coomer · Nov 27, 2014 · Viewed 14k times · Source

I need to check if an integer is divisible by another integer exactly.

If not I would like to round it up to the closest multiple of the number.

Example:

var numberOne = 3
var numberTwo = 5

numberTwo is not a multiple of numberOne therefore I would like it to round numberTwo up to 6.

How would I do this? Thank you

Answer

Antonio picture Antonio · Nov 27, 2014

You can use the modulo operator %:

numberTwo % numberOne == 0

The modulo finds the remainder of an integer division between 2 numbers, so for example:

20 / 3 = 6
20 % 3 = 20 - 6 * 3 = 2

The result of 20/3 is 6.666667 - the dividend (20) minus the integer part of that division multiplied by the divisor (3 * 6) is the modulo (20 - 6 * 3) , equal to 2 in this case.

If the modulo is zero, then the dividend is a multiple of the divisor

More info about the modulo at this wikipedia page.