Skip to the workspace
Pebellslearn by building
Variables and Data Types  ›  Lesson

Integers, Floats and Unsigned Numbers

Integers 15 minKotlin has signed whole-number types of four sizes, Double and Float for fractions, and unsigned types for values that are never negative, with no silent conversion between any of them.

kotlin / Integers, Floats and Unsigned Numbers

Explore each scene at your own pace.

01 · The rule

The rule

Integers, Floats and Unsigned Numbers

Kotlin has signed whole-number types of four sizes, Double and Float for fractions, and unsigned types for values that are never negative, with no silent conversion between any of them.

Choose numeric ranges and perform the explicit conversions a calculation requires.

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 round

Every 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.