kotlin-multiplatform-bignum icon indicating copy to clipboard operation
kotlin-multiplatform-bignum copied to clipboard

BigDecimal divideAndRemainder wrong results

Open sergeych opened this issue 1 year ago • 3 comments

Describe the bug The result of BigDecimal.divideAndRemainder are incorrect.:

 @Test
    fun testRemainder() {
        val full = BigDecimal.fromInt(360)
        val x = BigDecimal.fromDouble(15.5) + full*5

        val (q,r) = x.divideAndRemainder(full)
        assertEquals("5", q.toStringExpanded())  // got: 5.043 
        assertEquals("15.5", r.toStringExpanded())
    }
  • quotient must be a whole number first of all. The remainder is invalid too.

Platform

  • [JVM]

Additional context

I've checked it against java math BigDecimal, it works as expected:

    @Test
    fun testRemainder2() {
        val full = java.math.BigDecimal(360)
        val x = java.math.BigDecimal(15.5) + full*java.math.BigDecimal(5)

        val divrem = x.divideAndRemainder(full)
        assertEquals("5.0", divrem[0].toPlainString())
        assertEquals("15.5", divrem[1].toPlainString())
        // and the shortcut:
        assertEquals("15.5", (x % full).toPlainString())
    }

And thanks for this library and Happy New Year!

sergeych avatar Jan 04 '24 13:01 sergeych

The precision needed for rounding was not calculated properly. The fix should be available in snapshot soon. Thanks for reporting and happy new year as well!

ionspin avatar Jan 05 '24 11:01 ionspin

It's still counting wrong, if number is less then 1

` @Test fun roundNewText() { val one = "0.59".toBigDecimal() val two = "0.1".toBigDecimal()

    val result = one.divideAndRemainder(two)

    println("result=${result.second.toPlainString()}")
    // Result is "0.59"
}

@Test
fun roundNewText() {
    val one = "1.59".toBigDecimal()
    val two = "0.1".toBigDecimal()

    val result = one.divideAndRemainder(two)

    println("result=${result.second.toPlainString()}")
    // Here result is 0.09
}

`

makaronis avatar May 07 '24 10:05 makaronis

Thanks for reporting, I'll check it out when I have some free time.

ionspin avatar May 09 '24 06:05 ionspin