Kotlin Numbers
Numbers are values that Kotlin can add, subtract, multiply, and divide. Whole numbers and decimal numbers follow different rules when a division leaves a part over.
Int arithmetic
The four signs work on whole numbers like plain maths. Each print shows the result of one sign.
fun main() {
val a = 12
val b = 4
println(a + b)
println(a - b)
println(a * b)
println(a / b)
}Int division drops the leftover part
Dividing whole numbers gives a whole number back. The result moves toward zero, so -7 / 2 gives -3 and not -4.
fun main() {
println(7 / 2)
println(-7 / 2)
}Remainder with %
The % sign gives what is left after a division. A negative first number keeps its sign in the leftover.
fun main() {
println(17 % 5)
println(10 % 2)
println(-5 % 3)
}Double arithmetic keeps decimals
One value with a decimal point makes the calculation decimal. The last line shows exactly what the computer prints for that decimal sum.
fun main() {
println(7.0 / 2)
println(2.5 * 4)
println(0.1 + 0.2)
}Changing a stored value
The signs +=, -=, and *= change a stored value in place. The sign ++ at the end adds one more.
fun main() {
var score = 10
score += 5
println(score)
score -= 3
println(score)
score *= 2
println(score)
score++
println(score)
}Example
fun main() {
val price = 4
val count = 3
println(price * count)
var change = 20 - price * count
println(change)
println(change % 3)
println(change / 2.0)
change++
println(change)
}Key points
- Int arithmetic: whole numbers work with +, -, *, and / like plain maths.
- Int division drops the part after the point and moves toward zero.
- Remainder: % gives what is left after one number is divided by another.
- Double arithmetic keeps decimal places in the result.
- Compound assignment: +=, -=, and *= change a stored value and keep the new value.
- ++ adds one to a stored value.
In this example, price is 4 and count is 3, so the first print shows the total cost 12. The change from 20 is 8. The remainder of 8 % 3 is 2, and 8 divided by 2.0 gives the decimal 4.0. The last line adds one to change and shows 9.
Note
A decimal sum can print with many digits after the point because a computer stores decimal values in a fixed space.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
What does println(9 / 2) print?