ionspin / kotlin-multiplatform-bignum

A Kotlin multiplatform library for arbitrary precision arithmetics
Apache License 2.0
369 stars 42 forks source link

Convert to / from Java BigDecimal #99

Closed dankito closed 2 years ago

dankito commented 4 years ago

Hi,

I created some extension methods to convert BigDecimal to / from Java BigDecimal (see below).

Two questions here:

package net.dankito.banking.extensions

import com.ionspin.kotlin.bignum.integer.Sign
import java.math.BigDecimal

fun BigDecimal.toIonspinBigDecimal(): com.ionspin.kotlin.bignum.decimal.BigDecimal {
    return com.ionspin.kotlin.bignum.decimal.BigDecimal.parseString(this.toString()) // TODO: couldn't figure out how to create BigDecimal from unscaledValue and scale
}

fun com.ionspin.kotlin.bignum.decimal.BigDecimal.toJavaBigDecimal(): BigDecimal {
    val converted = BigDecimal.valueOf(this.significand.longValue(), (this.precision - this.exponent - 1).toInt())

    if (this.significand.sign == Sign.NEGATIVE) {
        return converted.negate()
    }

    return converted
}
ionspin commented 4 years ago

Hi @dankito , if you find these converters useful, I'd love to add them to the library, so a pull request would be great.

As far as the correctness goes, conversion from java big decimal using string as intermediary would work, but I think it would be too inefficient, so I'd suggest solving that with a more direct approach (i.e. by using Java BigDecimal internal Java BigInteger intValue and scale)

For the conversion to Java Big Decimal, the result wouldn't be completely correct, because significand can be larger than a long, so just calling longValue() would lose information. There's already some conversion done in the test classes, so you might take some code from there as inspiration (https://github.com/ionspin/kotlin-multiplatform-bignum/blob/master/bignum/src/jvmTest/kotlin/com/ionspin/kotlin/bignum/decimal/DecimalUtility.kt)