Almost every program does some arithmetic: adding up a basket, working out a percentage, converting minutes into hours, picking a random number for a game. Kotlin uses the familiar symbols +, -, * and /, plus a few more you'll use constantly.
Like Java, Kotlin is strict about number types, and that affects results. Dividing one Int by another drops the decimal part, so 7 / 2 is 3. Mixing an Int with a Double gives a Double. Knowing these rules means your calculations come out right first time.
In this lesson you'll use the arithmetic operators, update variables with shortcuts such as +=, compare values and combine conditions, call math functions such as sqrt and round, generate random numbers, and format results to a fixed number of decimal places.
Arithmetic operators
| Operator | Meaning | Int example | Double example |
|---|---|---|---|
+ | Add | 7 + 2 is 9 | 7.5 + 2 is 9.5 |
- | Subtract | 7 - 2 is 5 | 7.5 - 2 is 5.5 |
* | Multiply | 7 * 2 is 14 | 2.5 * 3 is 7.5 |
/ | Divide | 7 / 2 is 3 | 7.0 / 2 is 3.5 |
% | Remainder | 7 % 2 is 1 | 7.5 % 2 is 1.5 |
When both sides are Int, / performs integer division and drops the decimals. Make one side a Double to keep them: 7.0 / 2 or total.toDouble() / count. The remainder operator % answers questions like "is this even?" (n % 2 == 0).
Shortcuts and precedence
Kotlin has shorthand for updating a var:
| Shortcut | Same as |
|---|---|
x += 5 | x = x + 5 |
x -= 5 | x = x - 5 |
x *= 2, x /= 2, x %= 3 | and so on |
x++ / x-- | add or subtract 1 |
Operators follow normal maths order: brackets first, then *, / and %, then + and -. So 2 + 3 * 4 is 14, while (2 + 3) * 4 is 20. Add brackets whenever they make your intention clearer.
Comparison and logic
Comparisons produce a Boolean: == (equal), != (not equal), <, >, <= and >=. In Kotlin, == compares values, even for strings, so "cat" == "cat" is true.
Combine conditions with && (and), || (or) and ! (not):
val age = 20
val hasTicket = true
println(age >= 18 && hasTicket) // true
println(!hasTicket) // false&& and || stop early: if the left side of && is false, the right side isn't even checked.
Math functions, random numbers and formatting
Import what you need from kotlin.math:
sqrt(16.0)is4.0,abs(-7)is7, and2.0.pow(10)is1024.0.round(2.5)rounds to the nearest whole number (ties go to the even neighbour, so2.0),ceilrounds up andfloorrounds down.maxOf(a, b)andminOf(a, b)pick the larger or smaller value.
For random whole numbers, (1..6).random() picks one from the range. To show a fixed number of decimals, use "%.2f".format(price), which turns 3.5 into "3.50".
Rounding: round, roundToInt and formatting
Kotlin has several ways to round, and they don't all behave the same at exactly .5:
import kotlin.math.round
import kotlin.math.roundToInt
println(round(2.5)) // 2.0, rounds a tie to the even neighbour
println(2.5.roundToInt()) // 3, rounds a tie upwards
println(3.7.toInt()) // 3, simply cuts off the decimals
println("%.2f".format(3.14159)) // 3.14, for display onlyround uses "round half to even", which avoids bias when many values are rounded, so round(2.5) is 2.0 and round(3.5) is 4.0. roundToInt() returns an Int and rounds halves up. For display, format the number instead of changing it, and for money use java.math.BigDecimal, where BigDecimal("0.10") + BigDecimal("0.20") is exactly 0.30.
Kotlin Operators Syntax
Operators
a + b a - b a * b a / b a % b
x += 1 x++ x--
a == b a != b a < b a >= b
cond1 && cond2 cond1 || cond2 !cond
import kotlin.math.*
sqrt(x) abs(x) x.pow(2) round(x) ceil(x) floor(x)
(1..6).random()
"%.2f".format(price)Kotlin Operators Summary
/between two Ints drops the decimals; make one side a Double to keep them.%gives the remainder;+=,-=,++and--update a var.==,!=,<,>compare values;&&,||and!combine Booleans.- kotlin.math provides sqrt, abs, pow, round, ceil and floor.
(1..6).random()gives a random number;"%.2f".format(x)formats decimals.
Kotlin Operators Examples
Each example shows the code, the output it produces and what each part does.
Minutes, hours and even numbers
fun main() {
val minutes = 135
val hours = minutes / 60
val left = minutes % 60
println("$minutes minutes = $hours h $left min")
for (n in 1..6) {
if (n % 2 == 0) println("$n is even")
}
}135 minutes = 2 h 15 min
2 is even
4 is even
6 is evenLine-by-line explanation
- Line 3Integer division gives the whole hours.
- Line 4The remainder is the minutes left over.
- Line 5$name inside a string inserts the variable's value, as the strings lesson explains.
- Line 8A number is even when dividing by 2 leaves no remainder.
Averages and decimals
fun main() {
val total = 17
val count = 4
println(total / count)
println(total.toDouble() / count)
println("%.1f".format(total.toDouble() / count))
println(maxOf(total, 20))
}4
4.25
4.3
20Line-by-line explanation
- Line 5Both are Ints, so the .25 is lost.
- Line 6Converting one side to Double keeps the decimals.
- Line 7Formatting to one decimal place rounds 4.25 up to 4.3.
- Line 8maxOf returns the larger of the two values.
Math functions and a dice roll
import kotlin.math.pow
import kotlin.math.sqrt
import kotlin.math.abs
fun main() {
var score = 0
score += 50
score *= 2
score -= 15
score++
println("Score: $score")
println(sqrt(144.0))
println(2.0.pow(8))
println(abs(-42))
val roll = (1..6).random()
println("You rolled $roll")
}Score: 86
12.0
256.0
42
You rolled 4Line-by-line explanation
- Lines 7 to 100, then 50, 100, 85 and finally 86.
- Lines 13 to 14sqrt and pow work with Doubles and return Doubles.
- Line 17random picks any number from 1 to 6, so your roll may differ.
Common Kotlin Operators Mistakes
Integer division by accident
val half: Double = 1 / 2 // Type mismatch: Int can't be assigned to Doubleval half = 1.0 / 2 // 0.5Expecting toInt to round
val stars = 4.7.toInt() // 4val stars = kotlin.math.round(4.7).toInt() // 5Using = instead of == in a condition
if (score = 100) println("Perfect") // error: assignments are not expressionsif (score == 100) println("Perfect")Kotlin refuses to compile the first version, which prevents a classic bug.
Kotlin Operators in Real Projects
Numbers in Kotlin apps
Shopping apps calculate totals and taxes, fitness apps convert distances and paces, and games roll dice and move characters with these operators every frame. For money, professional apps often store amounts as whole pence or cents in a Long, or use Java's BigDecimal, to avoid the tiny rounding errors of Double.
Kotlin Operators FAQ
Does Kotlin have a power operator?
No. Use the pow function from kotlin.math: 2.0.pow(10) is 1024.0. It works on Double and Float, so convert an Int first with toDouble(), and convert the result back with toInt() if you need a whole number.
Why does -7 % 3 give -1 in Kotlin?
The % operator gives the remainder, which takes the sign of the left-hand number. If you need a result between 0 and the divisor, for example to wrap around a circular list, use mod: (-7).mod(3) is 2.
How do I generate a random number in Kotlin?
Call random() on a range: (1..6).random() gives a dice roll from 1 to 6. Random.nextInt(1, 7) from kotlin.random does the same, but its upper bound is exclusive. For repeatable results in tests, create a seeded generator: Random(42).
How do I detect integer overflow?
Ordinary Int arithmetic wraps silently, so Int.MAX_VALUE + 1 becomes a large negative number. On the JVM, Math.addExact(a, b) and Math.multiplyExact(a, b) throw an ArithmeticException with the message "integer overflow" instead. Using Long gives a much larger range.
Why is 0.1 + 0.2 not exactly 0.3?
Double stores numbers in binary, and 0.1 can't be represented exactly, so the sum prints as 0.30000000000000004. Format results for display, compare decimals with a small tolerance, and use BigDecimal or whole cents for money.
Kotlin Operators Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the code so it prints the remainder of 17 divided by 5.
println(17 5)
What does println(9 / 2) print?
What does this print?
var x = 10
x -= 3
x *= 2
println(x)
Which expression is true only when age is from 13 to 19?
How do you show 2.5 as "2.50"?
Kotlin Operators Quiz
5 questions to check what you learned.
What is
2 + 3 * 4in Kotlin?- 20
- 14
- 24
- 9
What does
==compare for two strings in Kotlin?- Their memory addresses
- Their lengths only
- Nothing, it's an error
- Their text values
What does
(1..6).random()return?- Always 1
- A random Int from 1 to 6, inclusive
- A random Double
- A list of six numbers
Which type should you use for a value like 5,000,000,000?
- Int
- Char
- Boolean
- Long
What does
true || println("hi") == Unitevaluate, and is "hi" printed?- true, and hi is not printed
- false, and hi is printed
- true, and hi is printed
- An error