Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 134 ยท Getting Started

Working with Numbers

Calculate with numbers in Kotlin - integer division, remainder, overflow, rounding, kotlin.math, BigInteger and BigDecimal for exact results, and unsigned types.

Numbers are the oldest job of a computer, and Kotlin gives you everything you need to calculate with them correctly: the usual operators, a kotlin.math package, safe parsing functions, exact arithmetic for money and huge integers, and unsigned types for binary data. The traps are the same as in every language, such as integer division, overflow and floating-point rounding, and this lesson shows each one fail before showing the fix.

If the previous lesson on basic types taught you what a number is, this one teaches you how to compute with it.

Arithmetic

The arithmetic operators are +, -, *, / and % (remainder). Multiplication and division bind tighter than addition and subtraction, and parentheses override everything.

Kotlin The five arithmetic operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Integer division and remainder

When both sides are integers, / throws away the fraction (it truncates toward zero) and % gives what was left over. Together they obey the rule a == (a / b) * b + a % b. Both are everywhere in real code: splitting seconds into minutes and seconds, deciding whether a number is even, wrapping around a list.

Kotlin Breaking seconds into hours, minutes and seconds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The remainder of a negative number is negative: -7 % 2 is -1. That is why an odd check should be written n % 2 != 0. If you need a result that is always between 0 and b - 1, use mod, which returns the mathematically expected value: (-7).mod(5) is 3, while -7 % 5 is -2.

Kotlin % versus mod

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Dividing by zero

Integer division by zero is an exception. Floating-point division by zero is not.

Kotlin Integer division by zero (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The run ends with Exception in thread "main" java.lang.ArithmeticException: / by zero and a stack trace pointing at MainKt.main(main.kt:3). With Double, 100.0 / 0.0 gives Infinity silently. Check the divisor before dividing, or decide on a meaningful result for the empty case:

Kotlin
val average = if (items == 0) 0.0 else total.toDouble() / items

Compound assignment and increments

+=, -=, *=, /= and %= update a var. ++ and -- add or subtract one, and may come before or after the variable.

Kotlin Updating variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Used as a value, i++ returns the old value and ++i the new one. Beginners are best served by writing the increment on its own line.

Overflow and exact arithmetic

As you saw earlier, an Int wraps around silently at about 2.1 billion. This is a classic bug in factorial or Fibonacci code. The standard library offers a way to turn silent wrap-around into a loud error: the Math.*Exact functions from Java throw an ArithmeticException on overflow.

Kotlin Factorial with silent overflow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

13! is 6,227,020,800 which does not fit in an Int, so the program prints a wrong number without any complaint (1932053504 for 13!, and the negative -2102132736 for 20!). Two fixes: widen the type (a Long fits up to 20!) or detect the overflow.

Kotlin Detecting overflow with Math.multiplyExact (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

safeFactorial(12) prints 479001600. The second call stops the program with java.lang.ArithmeticException: integer overflow. A loud error is far better than a quietly wrong number.

Math functions

Common functions live in the package kotlin.math, which you import. Many are also available as properties of the number itself.

Kotlin kotlin.math in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice that pow is written as an extension on the number (2.0.pow(10)), not as pow(2.0, 10.0): kotlin.math has no top-level pow function, and the compiler answers unresolved reference 'pow'. if you try.

Rounding

Rounding is a frequent need and the standard library has several flavors. round rounds to the nearest whole number, with halves going to the nearest even number ("banker's rounding"). roundToInt() and roundToLong() return an integer type, and they round halves upward.

Kotlin Rounding in all directions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

For two decimal places the multiply-round-divide trick is fine for display, while "%.2f".format(x) gives you a string, which is usually what you want for output. Never use these tricks for accounting; use BigDecimal below.

Parsing numbers from text

Text must be converted before you can calculate with it. toInt() throws a NumberFormatException for bad input. toIntOrNull() returns null instead, which you can handle with ?:. There are equivalents for every type: toLong(), toDouble(), toDoubleOrNull() and so on.

Kotlin Safe and unsafe parsing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Exact numbers: BigInteger and BigDecimal

Two classes from the Java library fix the limits of the built-in types: BigInteger has unlimited size, and BigDecimal stores decimal fractions exactly. Kotlin makes them pleasant, since you can use the normal operators on them and convert from numbers with toBigInteger() / toBigDecimal().

Kotlin Factorial of 30 with BigInteger

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

30! has 33 digits; no built-in type could hold it. Now money. Binary floating point cannot represent 0.10 exactly, so adding dimes goes slightly wrong, but BigDecimal made from a string is exact.

Kotlin Money with BigDecimal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Two important details. First, create a BigDecimal from a String (BigDecimal("0.10")), not from a Double, otherwise you freeze the inexact binary value into it. Second, == on BigDecimal compares the scale too: BigDecimal("1.0") == BigDecimal("1.00") is false. Use compareTo(...) == 0 to compare the numeric value. When dividing, always provide a scale and rounding mode; otherwise a non-terminating result such as 1/3 throws an ArithmeticException.

Unsigned integers

Sometimes negative numbers make no sense: byte values from a file, pixel colors, hash values. Kotlin offers UByte, UShort, UInt and ULong, with literals ending in u or U. They have the same sizes as their signed cousins but cover the range 0 up to double the signed maximum.

Kotlin Unsigned types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Unsigned arithmetic wraps around too, so 3u - 5u gives a huge number rather than -2. Use unsigned types for bit patterns and binary protocols (see Bits and Bytes), not as a way to "forbid negative values" in everyday business logic; a validated Int is a better choice there.

Choosing the right numeric type

  • Counting things, indexes, sizes: Int. Counts that may pass two billion, file sizes, timestamps in milliseconds, database ids: Long.
  • Measurements, scientific values, graphics: Double.
  • Money and anything where 0.1 + 0.2 must equal 0.3: BigDecimal (or integer cents in a Long).
  • Huge whole numbers such as factorials and cryptography: BigInteger.
  • Raw bytes and bit fields: UByte/UInt, together with bit operations.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does 17 / 5 evaluate to in Kotlin?

    Both operands are Int, so the result is an Int and the fractional part is discarded. 17 % 5 is the remainder, 2.
  2. 2. What is -7 % 5?

    The sign of % follows the left operand, so the result is -2. (-7).mod(5) returns 3, which is always non-negative for a positive divisor.
  3. 3. Why should money be stored in BigDecimal (created from a String) instead of Double?

    Doubles are binary approximations, so sums of decimal amounts drift. BigDecimal built from strings keeps the exact decimal value.
  4. 4. What happens when you run 100 / 0 with Int values?

    Integer division by zero throws ArithmeticException: / by zero. Only floating-point division gives Infinity or NaN.
  5. 5. Which function returns null instead of throwing when the text is not a number?

    toIntOrNull() returns null for invalid input, which pairs nicely with the elvis operator ?:.

Summary

  • / between integers truncates; use a Double operand for a fractional result. % keeps the sign of the dividend, while mod gives a non-negative result.
  • Integer division by zero throws ArithmeticException; floating-point division gives Infinity or NaN.
  • Integer overflow wraps silently; Math.addExact and friends turn it into an exception, and Long or BigInteger give more room.
  • kotlin.math provides abs, sqrt, pow, floor, ceil, round, roundToInt and more.
  • Use toIntOrNull(), toDoubleOrNull() and so on to parse untrusted text.
  • Use BigDecimal("...") for exact decimals (compare with compareTo) and BigInteger for unlimited integers.
  • Unsigned types (UInt, UByte, ...) are for bit patterns and binary data.

Next: Strings