BigInteger and BigDecimal

suggest change

Standard primitive types have strict precision and size limits:

To perform exact financial calculations and handle arbitrary-precision numbers, Kotlin integrates java.math.BigInteger and java.math.BigDecimal with first-class operator overloading and standard library extension functions.


Creating BigInteger and BigDecimal

Kotlin provides clean extension functions to construct big numbers from primitives and strings:

import java.math.BigDecimal
import java.math.BigInteger

fun main() {
    // From Strings (Recommended for exactness)
    val bigInt = "123456789012345678901234567890".toBigInteger()
    val price = "19.99".toBigDecimal()

    // From Primitives
    val intVal = 42.toBigInteger()
    val longVal = 1000000L.toBigInteger()
    val doubleVal = 49.95.toBigDecimal()

    // Constants
    val zero = BigInteger.ZERO
    val one = BigDecimal.ONE
    val ten = BigDecimal.TEN
}

Important: Prefer constructing BigDecimal from a String (e.g., "0.1".toBigDecimal()) rather than a Double. Because 0.1 cannot be represented precisely in binary floating-point, the Java constructor BigDecimal(0.1) introduces rounding noise (0.1000000000000000055511151231257827021181583404541015625). Kotlin's 0.1.toBigDecimal() goes through Double.toString() and gives 0.1, but a Double that is already the result of arithmetic carries its error along: (0.1 + 0.2).toBigDecimal() is 0.30000000000000004.


Operator Overloading in Kotlin

Unlike Java, where every calculation requires verbose method calls like .add() and .multiply(), Kotlin overloads standard mathematical and comparison operators:

import java.math.BigDecimal
import java.math.BigInteger

fun main() {
    val a = 150.toBigInteger()
    val b = 25.toBigInteger()

    // Arithmetic operators
    val sum = a + b        // a.add(b)
    val diff = a - b       // a.subtract(b)
    val product = a * b    // a.multiply(b)
    val quotient = a / b   // a.divide(b)
    val remainder = a % b  // a.remainder(b)
    val negated = -a       // a.negate()

    println("Sum: $sum, Product: $product")

    // Comparison operators
    val x = "100.50".toBigDecimal()
    val y = "200.00".toBigDecimal()

    println(x < y)  // true: x.compareTo(y) < 0
    println(x >= y) // false
    println(x == "100.50".toBigDecimal()) // true
}

BigInteger: Large Factorial Example

BigInteger can compute integers with millions of digits without overflowing:

import java.math.BigInteger

fun factorial(n: Int): BigInteger {
    var result = BigInteger.ONE
    for (i in 2..n) {
        result *= i.toBigInteger()
    }
    return result
}

fun main() {
    println("50! = ${factorial(50)}")
    // 30414093201713378043612608166064768844377641568960512000000000000
}

BigDecimal: Financial Math and Rounding Modes

When dividing decimals, fractions like $1/3$ result in an infinite repeating expansion. If no scale or rounding mode is specified, divide() throws an ArithmeticException: Non-terminating decimal expansion.

Always specify a scale and a RoundingMode:

import java.math.BigDecimal
import java.math.RoundingMode

fun main() {
    val subtotal = "129.50".toBigDecimal()
    val taxRate = "0.0825".toBigDecimal()

    // Compute tax with 2 decimal places using HALF_UP (standard commercial rounding)
    val rawTax = subtotal * taxRate
    val tax = rawTax.setScale(2, RoundingMode.HALF_UP)
    val total = subtotal + tax

    println("Subtotal: $$subtotal")
    println("Tax:      $$tax")   // $10.68
    println("Total:    $$total") // $140.18

    // Division with explicit scale and rounding
    val splitCount = 3.toBigDecimal()
    val perPerson = total.divide(splitCount, 2, RoundingMode.HALF_EVEN)
    println("Each person pays: $$perPerson") // $46.73
}

Scale vs Precision

fun main() {
    val num = "123.4560".toBigDecimal()
    println("Scale: ${num.scale()}")         // 4
    println("Precision: ${num.precision()}") // 7

    // Strip trailing zeros
    val stripped = num.stripTrailingZeros()
    println("Stripped: $stripped (Scale: ${stripped.scale()})") // 123.456 (Scale: 3)
}

Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents