Unobvious BigDecimal.div


#1

Good afternoon, below I’ve attached source code of overloading of divide operator for BigDecimal.

@kotlin.internal.InlineOnly
public inline operator fun BigDecimal.div(other: BigDecimal):
BigDecimal = this.divide(other, RoundingMode.HALF_EVEN)

Was there any reason to use RoundingMode.HALF_EVEN and BigDecimal::divide(BigDecimal divisor, RoundingMode roundingMode) instead of BigDecimal::divide(BigDecimal divisor)?
This is not obvious, in my opinion, as it results in 12.0 / 100.0 = 0.0 instead of 12.0 / 100.0 = 0.12 if using BigDecimals.

I understand, that this may lead to ArithmeticException: “Non-terminating decimal expansion; no exact representable decimal result”, but in my opinion, this will be same way as for Java, and, therefore, more obvious.


#2

I am not 100% sure where your problem is. When I run this code

val a = BigDecimal("12.0")
val b = BigDecimal("100.0")
println(a / b)

The result is, as I would expect 0.1. BigDecimal does not change the precision of the decimal numbers. I guess the problem you have, is that you called the constructor of BigDecimal with a float and not with a String and therefor not properly setting the decimal precision of the number. If you want to get the exact result of 0.12 you will need to use BigDecimal("12.00").