BigInteger and BigDecimal
suggest changeStandard primitive types have strict precision and size limits:
Longoverflows beyond $9 \times 10^{18}$ (Long.MAX_VALUE).DoubleandFloatuse binary floating-point representation (IEEE 754), resulting in rounding inaccuracies (e.g.,0.1 + 0.2 != 0.3).
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
BigDecimalfrom aString(e.g.,"0.1".toBigDecimal()) rather than aDouble. Because0.1cannot be represented precisely in binary floating-point, the Java constructorBigDecimal(0.1)introduces rounding noise (0.1000000000000000055511151231257827021181583404541015625). Kotlin's0.1.toBigDecimal()goes throughDouble.toString()and gives0.1, but aDoublethat is already the result of arithmetic carries its error along:(0.1 + 0.2).toBigDecimal()is0.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
- Precision: Total count of significant digits in the number.
- Scale: Number of digits to the right of the decimal point.
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
- Never use
FloatorDoublefor financial balances: Even small rounding artifacts compound into major discrepancies over thousands of ledger entries. - Parse from strings: Use
"0.1".toBigDecimal(), and never theBigDecimal(0.1)constructor. - Always specify rounding modes on division: Avoid runtime
ArithmeticExceptionby explicitly setting scale andRoundingMode.HALF_UPorRoundingMode.HALF_EVEN(banker's rounding). - Remember immutability: Both
BigIntegerandBigDecimalare immutable; operations like+return brand new instances.