In this tutorial, you shall learn about Modulus operator in Kotlin, its syntax, and how to use Modulus operator in programs, with examples.
Kotlin Modulus
Kotlin Modulus Operator takes two numbers as operands, divides the first number by the second number, and returns the remainder of this division operation.
%
symbol is used for Modulus Operator.
Syntax
The syntax for Modulus Operator is
operand_1 % operand_2
The operands could be of any numeric datatype.
Examples
1. Find remainder in the division operation
In the following example, we take two integers: a
and b
, and find the remainder of the division: a
divided by b
, using Modulus Operator.
Main.kt
fun main() {
var a = 20
var b = 3
var remainder = a % b
println("Remainder : $remainder")
}
Output
Remainder : 2
2. Find remainder with numbers of different types
In the following example, we divide a Float number by an Int number, and find the remainder of this division using Modulus Operator.
When a decimal is involved, the division happens till the quotient is an integer, and the left out part of the dividend is returned as remainder.
Main.kt
fun main() {
var a = 20.7
var b = 3.14
var remainder = a % b
println("Remainder : $remainder")
}
Output
Remainder : 1.8599999999999985
Conclusion
In this Kotlin Tutorial, we learned how to use Modulus Operator to find the remainder in the division of a number by another number.