Kotlin Modulus

Kotlin Modulus Operator

Kotlin Modulus operator is used to find the remainder in the division of given left operand by the given right operand.

Syntax

The syntax to use Arithmetic Modulus operator is

n1 % n2

where

  • n1 is the left operand
  • % is the symbol used for Modulus operator
  • n2 is the right operand

Return value

  1. If both operands are of type Int, the above modulus returns the remainder in the division of n1 by n2.
  2. If at least one of the operands is of type Double or Float, the modulus operator returns a Double or Float value, respectively.

Examples

Remainder in the Division of 11 by 3

In the following program, we take two variables: n1, and n2 with the values 11 and 3 respectively; and find the remainder in the division of n1 by n2.

Kotlin Program

fun main() {
    var n1 = 11
    var n2 = 3

    val result = n1 % n2
    println("n1 = $n1\nn2 = $n2\nn1 % n2 = $result")
}

Output

n1 = 11
n2 = 3
n1 % n2 = 2

Modulus in the Division of 6.28 by 2.1

In the following program, we find the remainder in the division of floating point numbers.

Kotlin Program

fun main() {
    var n1 = 6.28
    var n2 = 2.1

    val result = n1 % n2
    println("n1 = $n1\nn2 = $n2\nn1 % n2 = $result")
}

Output

n1 = 6.28
n2 = 2.1
n1 % n2 = 2.08