Integers, Floats and Unsigned Numbers
The café's till adds up prices, counts cups and tracks stock. Get the number type wrong and the average price comes out as a whole number, or a counter quietly wraps round to a huge negative value. Kotlin makes you choose number types on purpose.
The rule
Whole numbers by size, fractions by precision, never converted silently.
Whole numbers (signed) — they can be negative:
| Type | Bits | Roughly holds |
|---|---|---|
Byte |
8 | −128 to 127 |
Short |
16 | about ±32 thousand |
Int |
32 | about ±2.1 billion (the default) |
Long |
64 | about ±9.2 quintillion (suffix L) |
Fractions — Double (64 bits, about 15–16 significant digits, the default) and Float (32 bits, about 6–7 digits, suffix f).
Unsigned — UByte, UShort, UInt, ULong hold only zero and positive numbers, doubling the positive range. Write them with a u suffix: val stock = 250u.
Three rules that bite beginners:
val cups = 7
val total = 24
println(total / cups) // 3 — Int / Int drops the fraction
println(total.toDouble() / cups) // 3.4285714285714284
val big: Long = cups // error: no silent Int-to-Long
val big2: Long = cups.toLong() // fine
println(Int.MAX_VALUE + 1) // -2147483648 — overflow wraps roundEvery number type has conversion functions: toInt(), toLong(), toDouble(), toFloat(), toUInt() and so on. Converting a Double to Int cuts off the fraction: 3.9.toInt() is 3.
Doubles are stored in binary, so some decimals are approximate: 0.1 + 0.2 prints 0.30000000000000004. For money, count in the smallest unit (paise or cents) with Long, or use BigDecimal.
Unsigned numbers wrap too: 0u - 1u is 4294967295u, not −1.
The shortcut
Before any arithmetic, name the two types on each side of the operator. Both whole → whole result (fraction lost). Either is Double → Double. Different types in an assignment → you must call a to…() function.
The values
val cups = 45andval hours = 10, bothInt.
Drills
Answer fast — trust the rule.
What does println(9 / 2) print?
val cups: Int = 5. Which line compiles?
Which literal creates an unsigned integer?
What is 3.99.toInt()?
Why is Double a poor choice for adding up money exactly?
Remember
IntandDoubleare the defaults;L,fandupickLong,Floatand unsigned.- Int / Int drops the fraction; convert one side to Double first.
- No silent conversions: call
toLong(),toDouble()and friends.
