Numbers, Overflow and Explicit Conversion

Numbers, Overflow and Explicit Conversion in Kotlin: --- Bolted to the frame of the weighbridge at a limestone quarry is a mechanical counter with five brass…


The Analogy: The Quarry's Five-Wheel Load Counter

Bolted to the frame of the weighbridge at a limestone quarry is a mechanical counter with five brass wheels, each carrying the digits nought to nine. Every time a lorry rolls off the plate the linkage advances the right-hand wheel by one, and when that wheel passes nine it drags the wheel to its left round by one place. The whole assembly counts to 99999 and there is nowhere further for it to go, so on the next load every wheel rolls over together and the window reads 00000. There is no bell, no flag, no ink mark on the ticket roll. The counter does not know it has run out of wheels; it only knows how to advance.

Kotlin's integer types are that counter with a fixed number of wheels chosen at declaration time. An Int has thirty-two binary wheels, which reach 2147483647 and then roll to the most negative value the type can hold. A Long has sixty-four, and a Byte has eight. None of them report the rollover, because reporting it would cost an instruction on every single addition in the program and the hardware simply does not offer the check for free. The compiler chose the number of wheels when you wrote the type; everything after that is arithmetic that wraps.

The quarry also has two other instruments, and they are the reason conversions are written out by hand. The weighbridge reports whole kilograms on a printed ticket. The laboratory balance in the sample hut reports grams to two decimal places on a paper tape. A figure from one cannot simply be copied onto the other's form: somebody has to multiply, and the act of multiplying is where a decision gets made about precision, rounding and what happens when the result is too big for the box on the form. Kotlin makes you write .toLong() and .toDouble() for exactly this reason -- there is no implicit widening, so every change of instrument is visible on the line where it happens.

The failure mode is the end-of-month reconciliation. The counter has rolled over once during a busy month, so the clerk subtracts the opening reading from the closing reading and gets a negative number of loads. The figure is impossible, and because the sheet has a column for it the figure is nonetheless entered, carried into the tonnage, divided by the number of working days, and reported as a productivity number that nobody can explain. In Kotlin that is a total that goes negative halfway through a loop and a report that balances perfectly against its own wrong arithmetic. The counter did not lie; it ran out of wheels, and nothing in the paperwork asked whether it might have.


Syntax or Core Structure

Every numeric literal has a type before you do anything with it, and the type follows from the shape of the literal and the declared type of the thing it is assigned to. Notice that the widening on the second-to-last line is written out: Kotlin has no implicit conversion between numeric types, not even from Int to Long where nothing could possibly be lost.

fun main() {
    val loads: Int = 3
    val capacity: Long = 3_500_000_000L      // beyond Int range, so it must be Long
    val mass: Double = 12.75
    val fraction: Float = 0.5f
    val flags: Int = 0b1010_1100
    val mask: Int = 0xFF

    println("loads: $loads")
    println("capacity: $capacity")
    println("mass: $mass")
    println("fraction: $fraction")
    println("flags: $flags")
    println("mask: $mask")

    val widened: Long = loads.toLong()       // explicit; Int does not become Long by itself
    println("widened + capacity: ${widened + capacity}")
    println("mass to int: ${mass.toInt()}")
    println("int division: ${7 / 2}  double division: ${7 / 2.0}")
}

Output:

loads: 3
capacity: 3500000000
mass: 12.75
fraction: 0.5
flags: 172
mask: 255
widened + capacity: 3500000003
mass to int: 12
int division: 3  double division: 3.5

The two number bases print as decimal because the base is a property of the literal and not of the value: 0b1010_1100 is one hundred and seventy-two written in binary, and the underscores are ignored entirely by the compiler, so they can go wherever they help a reader group digits. 0xFF is two hundred and fifty-five for the same reason. The L suffix on the capacity is habit rather than requirement -- a literal too large for Int is typed Long automatically -- but writing it means the type is visible without working out the magnitude. The last two lines are the pair worth memorising: 7 / 2 is integer division and gives three because both operands are Int, while 7 / 2.0 promotes and gives three point five. The operator did not change; the operand types did.


Technical Depth: Fixed Widths, Silent Wrap-Around and the Absence of Implicit Conversion

Kotlin's numeric types map onto the machine's own types. That is why they are fast, and it is also why they behave like the counter on the weighbridge rather than like the numbers in a mathematics textbook.

How many wheels each type has

typebitslowest valuehighest value
Byte8-128127
Short16-3276832767
Int32-21474836482147483647
Long64-92233720368547758089223372036854775807
UInt3204294967295
ULong64018446744073709551615
Float32about 7 significant decimal digitsnot a range but a precision
Double64about 15 significant decimal digitsnot a range but a precision

An unadorned integer literal is an Int if it fits and a Long if it does not, and an unadorned decimal literal is always a Double, never a Float. That last rule catches people: val f: Float = 1.5 does not compile, because 1.5 is a Double and Kotlin will not narrow it for you. The suffix f is how you say you meant the narrower type.

What each conversion does to the value

conversionbehaviourwhen it loses something
Int.toLong()widens exactlynever
Long.toInt()keeps the low 32 bitsany value outside Int range, silently
Int.toByte()keeps the low 8 bitsany value outside -128 to 127, silently
Double.toInt()truncates towards zeroevery fractional part; NaN becomes 0
Int.toDouble()widens exactlynever, for Int
Long.toDouble()rounds to the nearest representableany magnitude above 2^53
Double.toFloat()rounds to 32-bit precisiondigits beyond the seventh, and extreme magnitudes
String.toInt()parses or throwsthrows NumberFormatException on bad input
String.toIntOrNull()parses or returns nullnothing; the failure becomes a value

The two rows that keep low bits are the dangerous ones, because they are the only conversions in the table that produce a plausible-looking wrong answer rather than an obviously wrong one. Long.toInt() on a value of four billion does not clamp to Int.MAX_VALUE and does not throw; it discards the high half of the bit pattern and hands back whatever the remaining thirty-two bits happen to mean.

Overflow is silent, and the wrap is exact

fun ceiling(): Int = Int.MAX_VALUE

fun main() {
    val max = ceiling()
    println("max: $max")
    println("max + 1: ${max + 1}")
    println("wrapped to the minimum: ${max + 1 == Int.MIN_VALUE}")

    val widenedFirst: Long = max.toLong() + 1
    println("widened first: $widenedFirst")

    val big: Long = 4_294_967_298L
    println("big.toInt(): ${big.toInt()}")
    println("low 32 bits: ${big and 0xFFFFFFFFL}")

    try {
        println("never printed: ${Math.addExact(max, 1)}")
    } catch (e: ArithmeticException) {
        println("addExact refused: ${e::class.simpleName}")
    }
}

Output:

max: 2147483647
max + 1: -2147483648
wrapped to the minimum: true
widened first: 2147483648
big.toInt(): 2
low 32 bits: 2
addExact refused: ArithmeticException

The wrap is not corruption and it is not undefined; it is arithmetic modulo 2 to the thirty-second, which is precisely what the hardware does. max + 1 lands exactly on Int.MIN_VALUE, and the third line proves it rather than asserting it. Line four is the fix, and the order matters: max.toLong() + 1 widens before adding, whereas (max + 1).toLong() would wrap first and then widen the wrong answer. The two lines about big demonstrate that toInt() is a bit-pattern operation -- four billion two hundred and ninety-four million nine hundred and sixty-seven thousand two hundred and ninety-eight is two more than 2 to the thirty-second, so the low thirty-two bits hold 2, and masking gives the same answer as converting. The last line uses java.lang.Math.addExact, which is a JVM-only API and the only thing here that will not compile for a Kotlin target other than the JVM; the exception type is printed rather than its message, because the message text is a JDK implementation detail.

Floating point is not decimal

import kotlin.math.round

fun main() {
    val a = 0.1
    val b = 0.2
    println("0.1 + 0.2 == 0.3: ${a + b == 0.3}")
    println("0.1 + 0.2 = ${a + b}")
    println("in pence: ${10L + 20L}")

    val nan1 = Double.NaN
    val nan2 = 0.0 / 0.0
    println("nan == nan: ${nan1 == nan2}")
    println("nan.equals(nan): ${nan1.equals(nan2)}")
    println("1.0 / 0.0 = ${1.0 / 0.0}")
    println("rounded to 2dp: ${round((a + b) * 100) / 100}")
}

Output:

0.1 + 0.2 == 0.3: false
0.1 + 0.2 = 0.30000000000000004
in pence: 30
nan == nan: false
nan.equals(nan): true
1.0 / 0.0 = Infinity
rounded to 2dp: 0.3

Neither nought point one nor nought point two has an exact binary representation, so their sum is the nearest double to nought point three plus a little, and printing it shows the little. The pence line is the whole remedy in one expression: count in the smallest unit you actually care about, as an integer, and the arithmetic is exact. The two NaN lines are a genuine Kotlin subtlety rather than a curiosity -- when the static type is Double, == follows IEEE 754 and NaN is equal to nothing including itself, but equals has to obey the reflexivity contract that collections depend on, so it reports true. That means a NaN inside a Set<Double> can be found and a NaN in a local variable cannot be compared, and isNaN() is the only test that reads the same in both worlds. Note also that 1.0 / 0.0 is Infinity rather than an exception, while integer 1 / 0 throws ArithmeticException: the same operator, two entirely different failure models.


Real World Example: The Quarry's Annual Tonnage, Counted Twice

The quarry weighs five loads on a representative day and the office wants the year's figure in grams, because the laboratory works in grams and the contract is written in grams. Nothing about that is unreasonable and nothing about it is difficult, and it overflows an Int anyway. The program below computes the same number twice, once in the type an unthinking implementation would choose and once in the type the magnitude requires, and then reconciles the difference so the size of the mistake is visible rather than merely wrong.

const val LOADS = "18500,21000,19750,22400,20353"
const val WORKING_DAYS = 250
const val G_PER_KG = 1000

fun main() {
    val kg = LOADS.split(",").map { it.toInt() }
    val dayKg = kg.sum()
    println("loads per day: ${kg.size}")
    println("day total kg: $dayKg")
    println("mean load kg, int division: ${dayKg / kg.size}")
    println("mean load kg, as double: ${dayKg.toDouble() / kg.size}")

    val yearKg = dayKg * WORKING_DAYS
    println("year total kg: $yearKg")

    val gramsInt = yearKg * G_PER_KG              // Int times Int: wraps silently
    val gramsLong = yearKg.toLong() * G_PER_KG    // widened first, then multiplied
    println("grams as Int: $gramsInt")
    println("grams as Long: $gramsLong")
    println("Int result went negative: ${gramsInt < 0}")

    val lost = gramsLong - gramsInt
    println("lost: $lost")
    println("wraps of 2^32: ${lost / 4_294_967_296L}")
    println("a whole number of wraps: ${lost % 4_294_967_296L == 0L}")

    val tonnes = gramsLong / 1_000_000
    val leftoverGrams = gramsLong % 1_000_000
    println("tonnes: $tonnes leftover g: $leftoverGrams")
    println("reconciles: ${tonnes * 1_000_000 + leftoverGrams == gramsLong}")
}

Output:

loads per day: 5
day total kg: 102003
mean load kg, int division: 20400
mean load kg, as double: 20400.6
year total kg: 25500750
grams as Int: -269053776
grams as Long: 25500750000
Int result went negative: true
lost: 25769803776
wraps of 2^32: 6
a whole number of wraps: true
tonnes: 25500 leftover g: 750000
reconciles: true

Follow the arithmetic rather than the prose. Five loads sum to 102003 kg, two hundred and fifty days of that is 25500750 kg, which is comfortably inside Int and gives no hint of trouble. Multiplying by a thousand to reach grams asks for 25500750000, which needs thirty-five bits, and the Int expression answers -269053776 without an exception, a warning or any change in the shape of the code. The only difference between the two grams lines is where .toLong() sits, and it has to sit before the multiplication: widening the wrapped result afterwards would carry the wrong number into a wider type and look even more convincing.

The reconciliation lines exist to make the failure legible. The difference between the two answers is 25769803776, which is exactly six times 2 to the thirty-second, and the modulus check proves it is a whole number of wraps rather than an unrelated discrepancy. That is a useful diagnostic to know: when two totals differ by an exact multiple of the type's range, the cause is overflow and not a missing record. A difference of some other shape means something else is wrong, and the two need different investigations.

The last pair of lines shows the other half of the discipline. Splitting the grams total into whole tonnes and a remainder uses integer division and the modulus operator together, and the check that the two recombine into the original is one comparison. Any time a quantity is decomposed into a quotient and a remainder for display, printing that recombination costs one line and catches the entire class of unit errors, because a wrong divisor makes it fail immediately.

The limits are worth naming precisely, and the first is a defect in the report itself. The design flaw is the mean: 102003 divided by five is 20400.6, and the integer line prints 20400, so the sheet now carries a day total of 102003 kg and a mean that reconstructs to 102000 kg for the same five loads. Two numbers on the same report contradict each other by three kilograms, nothing in the program notices, and a reader has no way to tell which one to trust. Printing a truncated mean beside an exact total is not a rounding nicety; it is a report that fails its own arithmetic, and the fix is to print the residual alongside the mean or to report the mean only in the form that keeps it. Beyond that: it.toInt() throws NumberFormatException on any malformed field, so one stray character loses the whole day; dayKg * WORKING_DAYS is itself one busy month away from overflowing, and nothing checks it; the units live only in the identifiers, so the compiler would accept yearKg * WORKING_DAYS as readily as yearKg * G_PER_KG; and WORKING_DAYS is a constant standing in for a real calendar that has holidays, shutdowns and weather in it.


Common Mistakes

  1. Expecting an Int to become a Long on its own. val n: Long = someInt does not compile, and that is deliberate: Kotlin removed implicit numeric widening because the JVM's implicit narrowing rules are a known source of bugs and the two cannot be separated cleanly. Write someInt.toLong(). The compiler error is the feature.
  1. Widening after the operation instead of before it. (a * b).toLong() multiplies two Int values, wraps if the product is too large, and then widens the wrong answer. a.toLong() * b performs the multiplication in sixty-four bits. The two expressions differ by the position of one call and by the correctness of the result.
  1. Assuming an exception on overflow. Nothing in Kotlin's integer arithmetic throws on wrap-around; Int.MAX_VALUE + 1 is a valid expression with a defined negative value. If you need the check, use Math.addExact and friends on the JVM, or compare against Int.MAX_VALUE before the operation, or use a wider type and stop worrying.
  1. Reaching for toInt() to shrink a Long. It keeps the low thirty-two bits, so a count of five billion becomes seven hundred and five million and change, with the same sign it happens to land on. If a value must be narrowed, decide what should happen when it does not fit -- clamp with coerceAtMost, fail with require, or keep the wider type.
  1. Integer division where a fraction was meant. percent = part / total * 100 is nought for every input where part is smaller than total, because the division happens first and truncates to zero. Either reorder to part * 100 / total and accept truncation at the end, or convert one operand with toDouble() and mean it.
  1. Using Double for money. Nought point one plus nought point two is not nought point three in binary floating point, and the error compounds through a ledger until a penny appears from nowhere. Count in the smallest unit as a Long, or use BigDecimal with an explicit scale and rounding mode when the domain demands decimal semantics.
  1. Comparing Double values with ==. Two computations that should agree mathematically often differ in the last bit, so equality is the wrong question; compare the absolute difference against a tolerance you can justify. And remember the NaN asymmetry: == says a NaN differs from itself while equals says it does not, so use isNaN() when that is what you mean.
  1. Letting toInt() do your rounding. Double.toInt() truncates towards zero, so 2.99 is 2 and -2.99 is -2, and Double.NaN.toInt() is 0 with no complaint. When you want rounding, say round(), floor() or ceil() from kotlin.math, and know which way each one goes for negative numbers.
  1. Confusing a character's code with its digit value. '7'.code is fifty-five, because that is where the digit seven sits in the character set, and '7'.digitToInt() is seven. Parsing a numeric string by subtracting character codes works right up until the input contains a character you did not expect, at which point it produces a number rather than an error.

Best Practices

  • Choose the type from the largest value the quantity can ever reach, not from the values in today's test data. Identifiers, timestamps in milliseconds, byte counts and money in minor units all outgrow Int, and the cost of Long is four bytes.
  • Put the conversion before the arithmetic. Any expression that multiplies two quantities and stores the result somewhere wider should widen its operands first, and reviewing for that one pattern catches most real overflow bugs.
  • Keep money and other exact quantities in integer minor units, and let the presentation layer divide by a hundred. If a domain genuinely needs decimal fractions, use BigDecimal and specify the scale and rounding mode at every operation that can produce more digits.
  • Use toIntOrNull() and toLongOrNull() at every boundary where the text came from outside the program. They turn a thrown exception into a value you can branch on, which is almost always what a parser wants.
  • Group digits in long literals with underscores, and prefer a named constant to a repeated magic number. 4_294_967_296L is readable; the same digits unbroken are not, and G_PER_KG says why the thousand is there.
  • Prefer kotlin.math over the platform's math class when the code might ever target more than the JVM. round, abs, floor, ceil and sqrt all exist there with the same names and multiplatform implementations.
  • Print or assert a reconciliation whenever a total is decomposed. Quotient times divisor plus remainder equals the original is one comparison, and it converts a whole family of silent unit errors into an immediate failure.
  • Compare floating-point results with an explicit tolerance and test isNaN() before using a value in a branch. A NaN that reaches a comparison makes every ordering test false at once, which is how a sort or a filter quietly loses records.

Practice Exercises

  1. Reproduce the overflow deliberately. Multiply an Int daily total by a number of days large enough to exceed Int.MAX_VALUE, print the wrapped result, then print the same product with .toLong() applied to the left operand. Divide the difference by 4_294_967_296 and confirm you get a whole number of wraps.
  1. Write fun meanWithResidual(values: List<Int>): Pair<Int, Int> returning the truncated mean and the residual, where residual is the total minus mean times count. Call it on the five quarry loads, print both numbers, and assert in a comment that mean times count plus residual equals the total the program printed.
  1. Print 0.1 + 0.2, the result of comparing it to 0.3 with ==, and the result of comparing it with an absolute tolerance of 1e-9. Then do the same sum in pence as Long values and print that. State in one comment which of the three answers you would put in an invoice.
  1. Write fun parseLoads(text: String): List<Int> that splits on commas, converts with toIntOrNull(), and prints the index and content of every field that fails to parse before returning only the successful ones. Feed it a string with a blank field and a field containing a letter, and print how many fields were accepted out of how many were offered.