Skip to content
AgileLogics
5 min read

Numbers

Prerequisites: Basic types and type inference

Kotlin's everyday number types are Int for whole numbers and Double for decimals.

Example

fun main() {
    println(7 + 2)
    println(7 - 2)
    println(7 * 2)
    println(7 / 2)
    println(7 % 2)
    println(7.0 / 2)
    println(7 / 2.0)
    println(10.0 / 3)
    println(-7 / 2)
}

Expected output

9
5
14
3
1
3.5
3.5
3.3333333333333335
-3

Line by line:

  • 7 / 2 is 3: dividing two Ints gives an Int, dropping the remainder (integer division). -7 / 2 is -3 — it rounds toward zero.
  • % gives the remainder, handy for checking whether a number is even.
  • If either side is a Double, the result is a Double.
  • Doubles are approximate: 10.0 / 3 shows the tiny rounding error built into how computers store decimals.

Converting between number types

Kotlin doesn't mix number variables of different types automatically. Convert explicitly:

fun main() {
    val items = 7
    val people = 2
    println(items.toDouble() / people)
    println(3.99.toInt())
    println(3.5.roundToIntSafe())
}

fun Double.roundToIntSafe() = kotlin.math.round(this).toInt()
3.5
3
4

toInt() truncates (cuts off the decimals). To round, use kotlin.math.round or roundToInt() from kotlin.math. (The last line of that example defines a small helper — an extension function, explained in Level 2.)

Useful functions

import kotlin.math.abs
import kotlin.math.max
import kotlin.math.pow
import kotlin.math.sqrt

fun main() {
    println(abs(-5))
    println(max(3, 9))
    println(2.0.pow(10))
    println(sqrt(16.0))
    println(10 % 5 == 0)
    println(17.coerceIn(1, 10))
    println("%.2f".format(3.14159))
}
5
9
1024.0
4.0
true
10
3.14

"%.2f".format(x) formats a number with two decimal places.

Common mistakes

  • Integer overflow. Int.MAX_VALUE + 1 silently wraps around to a large negative number. Use Long for values that can exceed about 2.1 billion, such as millisecond timestamps.
  • Using Double for money. 0.1 + 0.2 is 0.30000000000000004. Store cents as Long, or use java.math.BigDecimal.

Practice

A pizza has 8 slices shared by 3 people. Print how many whole slices each person gets, how many are left over, and the exact share with two decimal places.

Show solution
fun main() {
    val slices = 8
    val people = 3
    println(slices / people)
    println(slices % people)
    println("%.2f".format(slices.toDouble() / people))
}
2
2
2.67