ionspin / kotlin-multiplatform-bignum

A Kotlin multiplatform library for arbitrary precision arithmetics
Apache License 2.0
339 stars 40 forks source link

ROUND_HALF_TO_EVEN and ROUND_HALF_TO_ODD not working properly #269

Closed CodeServant closed 6 months ago

CodeServant commented 8 months ago

Describe the bug Seems that when it comes to negative values rounding mode ROUND_HALF_TO_EVEN and ROUND_HALF_TO_ODD works just by rounding half to negative infinite -1.005 to -1.01, -1.015 to -1.02 and so on.

To Reproduce

val stringNum = "-1.005"
val bd1 = stringNum.toBigDecimal()
println("number is: $bd1")
println(
    "kotlin BD: " + BigDecimal.fromBigDecimal(
        bd1,
        DecimalMode(20, roundingMode = RoundingMode.ROUND_HALF_TO_EVEN, scale = 2)
    )
)
println("java BD: " + java.math.BigDecimal(stringNum, MathContext(3, java.math.RoundingMode.HALF_EVEN)))

Expected behavior RoundingMode.ROUND_HALF_TO_EVEN, scale 2 In my understading in this mode -1.005 should round to -1.00 because 0 is closer even number but in this case the result is -1.01 -1.015 should round to -1.02 because 2 is closer even number and the result is correct 1.005 should round to 1.00 because 0 is closer even number and the result is correct 1.015 should round to 1.02 because 2 is closer even number and the result is correct

Platform

Additional context I belive this is a bug because java java.math.RoundingMode.HALF_EVEN works as expected. This seems not to be the case with positive values.

ionspin commented 8 months ago

Thanks for reporting, a pull request with a fix would be highly appreciated!

CodeServant commented 8 months ago

I created a pull request with some tests. Please check if everything is correct,

ionspin commented 6 months ago

Fixed in #270