Checking an integer is divisible by another integer (Swift)

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

If not, I would like to round it to the nearest multiple.

Example:

var numberOne = 3 var numberTwo = 5 

numberTwo not a multiple of numberOne , so I would like to round numberTwo to 6.

How can I do it? Thanks you

+7
source share
3 answers

You can use the modulo % operator:

 numberTwo % numberOne == 0 

Modulo finds the remainder of the integer division between two numbers, 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 this division, multiplied by the divisor (3 * 6), is the module (20 - 6 * 3), equal to 2 in this case.

If the module is equal to zero, then the dividend is a multiple of the divisor

More information about the module on the page of this wikipedia page.

+15
source

You can use truncatingRemainder . For instance,

 if number.truncatingRemainder(dividingBy: 10) == 0 { print("number is divisible by 10") } 
+2
source

1) If you want to check or an integer is divisible by another integer:

Swift 5

 if numberOne.isMultiple(of: numberTwo) { ... } 

Swift 4 or less

 if numberOne % numberTwo == 0 { ... } 

2) The function of rounding to the nearest multiple value:

 func roundToClosestMultipleNumber(_ numberOne: Int, _ numberTwo: Int) -> Int { var result: Int = numberOne if numberOne % numberTwo != 0 { if numberOne < numberTwo { result = numberTwo } else { result = (numberOne / numberTwo + 1) * numberTwo } } return result } 
0
source

Source: https://habr.com/ru/post/1207831/


All Articles