Kotlin Division

Kotlin Division Operator

Kotlin Division operator is used to find the quotient in the division of left operand by right operand.

Syntax

The syntax to use Arithmetic Division operator is

n1 / n2

where

  • n1 is the left operand
  • % is the symbol used for Division Operator
  • n2 is the right operand

Return Value

The above expression returns the quotient in the division of n1 by n2. The data type of the return value depends on the given values.

Chaining Division Operator

We can also chain the operator to divide the number by more than one number.

n1 / n2 / n3

the above expression would be equivalent to

(n1 / n2) / n3

Note: For integer division, the remainder is discarded.

Examples

Division of 10 by 3

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

Kotlin Program

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

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

Output

n1 = 10
n2 = 3
n1 / n2 = 3

Division by more than one number

In the following program, we take three integer variables: n1, n2, and n3, and find the division of n1 by both n2 and n3.

Kotlin Program

fun main() {
    var n1 = 40
    var n2 = 2
    var n3 = 6

    val result = n1 / n2 / n3
    println("n1 / n2 / n3 = $result")
}

Output

n1 / n2 / n3 = 3

Explanation

n1 / n2 = 40 / 2
        = 20

n1 / n2 / n3 = (n1 / n2) / n3
             = 20 / n3
             = 20 / 6
             = 3

Division of 6.28 by 2.1

In the following program, we find 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.9904761904761905

Datatype of the returned value

the datatype of the value returned by the Division operator depends on the data types of the operands involved in the division. Here are the rules:

  1. If both operands are of type Int, the division operator / performs integer division and returns an Int value. The result is the quotient of the division, discarding any remainder.
  2. If at least one of the operands is of type Double or Float, the division operator / performs floating-point division and returns a Double or Float value, respectively. The result includes the fractional part.
  3. If one of the operands is an integral type (Int, Long, Short, Byte) and the other is a floating-point type (Double or Float), the division operator / performs floating-point division and returns a Double or Float value.
  4. If one of the operands is a floating-point type (Double or Float) and the other is a type that can hold larger numbers (Long, BigInteger), the division operator / performs floating-point division and returns a Double or Float value.