Skip to content

Kt-Math

Arbitrary-precision integers, decimals and rationals for Kotlin Multiplatform, usable from Kotlin, Java, JavaScript and C.

Kt-Math offers the API of Java's java.math.BigInteger and java.math.BigDecimal (plus a BigRational type) on every Kotlin platform, each backed by the fastest implementation available there:

Platform BigInteger BigDecimal, BigRational
JVM (Java 8+) java.math.BigInteger java.math.BigDecimal; Kotlin BigRational
JavaScript (Node.js, browsers) native BigInt Kotlin port of java.math.BigDecimal, on BigInts
Kotlin/Native (all targets) Kotlin port of java.math.BigInteger, with C kernels for the hot loops Kotlin port

The Kotlin port follows the JDK sources line by line, and its results are checked against java.math on every platform: the same operation gives the same result (and throws the same exception) everywhere.

        val x = BigInteger.of("123456789012345678901234567890")
        val y = 42.toBigInteger()
        assertEquals("5185185138518518513851851851380", (x * y).toString())
        assertEquals("2939447357436801878600823045", (x / y).toString())
        assertEquals("7", (x % 11.toBigInteger()).toString())
        assertEquals("1000", (BigInteger.TEN pow 3).toString())
        assertEquals("ff", 255.toBigInteger().toString(16))
        assertTrue(x > y)
        assertFailsWith<ArithmeticException> { x / BigInteger.ZERO }

Where to go next