Swift - Operator Modulus Operator

Introduction

The modulus operator % returns the remainder of a division.

For example, if you divide five by three, the remainder is two.

The following shows how the % operator works:

Demo

print(8 % 9)     //modulo (8)
print(9 % 8)     //modulo (1)
print(9 % 9)     //modulo (0)

Result

The modulus operator also works with a negative number:

print(-5 % 3)    //module (-2)

If the second operand is a negative number, the negative value is always ignored:

Demo

//negative value for second number is always ignored---
print(-5 % -3)   //module (-2)---

Result

The modulus operator also works with double values:

Demo

print(5 % 3.5)   //module (1.5)---
print(5.9 % 3.5) //module (2.4)---

Related Topic