Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The % operator in Kotlin is the arithmetic remainder operator. It calculates the remainder of the truncated division of the left operand (dividend) by the right operand (divisor). Under the hood, Kotlin implements the % operator via operator overloading. When you use %, the Kotlin compiler translates it into a call to the rem() member function.
val dividend = 10
val divisor = 3

// Standard operator syntax
val result1 = dividend % divisor 

// Equivalent explicit function call
val result2 = dividend.rem(divisor) 

Sign Mechanics

Unlike a strict mathematical modulo operation, Kotlin’s remainder operator preserves the sign of the dividend (the left operand). The sign of the divisor (the right operand) has no effect on the sign of the result.
 5 %  3  // Returns  2
-5 %  3  // Returns -2
 5 % -3  // Returns  2
-5 % -3  // Returns -2

Floating-Point Operands

The % operator is fully supported for Float and Double types. It adheres to the IEEE 754 standard for floating-point arithmetic, calculating the exact remainder without implicit rounding.
5.5 % 2.0  // Returns 1.5
5.0 % 1.5  // Returns 0.5

Edge Cases and Exceptions

The behavior of the % operator when encountering a zero divisor depends strictly on the operand types:
  • Integer Types (Int, Long, Short, Byte): Attempting to calculate the remainder with a divisor of 0 throws a java.lang.ArithmeticException.
  • Floating-Point Types (Float, Double): Attempting to calculate the remainder with a divisor of 0.0 does not throw an exception; instead, it evaluates to NaN (Not a Number).
10 % 0     // Throws ArithmeticException: / by zero
10.0 % 0.0 // Returns NaN

Custom Implementation

Because % maps to the rem() function, you can define the remainder operator for custom classes by utilizing the operator modifier.
class Vector(val x: Int, val y: Int) {
    operator fun rem(divisor: Int): Vector {
        return Vector(x % divisor, y % divisor)
    }
}

val v1 = Vector(10, 15)
val v2 = v1 % 4 // Evaluates to Vector(2, 3)
(Note: In Kotlin versions prior to 1.1, the % operator mapped to the mod() function. This was deprecated and replaced by rem() to accurately reflect that the operation performs a truncated division remainder rather than a Euclidean modulo).
Master Kotlin with Deep Grasping Methodology!Learn More