Joel
07/14/2020, 8:49 PMBigDecimal
extensions in the kotlin
package:
operator fun BigDecimal.plus(other: BigDecimal): BigDecimal = add(other, MathContext.DECIMAL128)
operator fun BigDecimal.minus(other: BigDecimal): BigDecimal = subtract(other, MathContext.DECIMAL128)
operator fun BigDecimal.div(other: BigDecimal): BigDecimal = divide(other, MathContext.DECIMAL128)
operator fun BigDecimal.times(other: BigDecimal): BigDecimal = multiply(other, MathContext.DECIMAL128)
The default implementation for div
is:
@kotlin.internal.InlineOnly
public inline operator fun BigDecimal.div(other: BigDecimal): BigDecimal = this.divide(other, RoundingMode.HALF_EVEN)
This will allow my implementation to always use DECIMAL128
standard math context for all operations, eliminating any precision issues (for example 1.toBigDecimal() / 3.toBigDecimal()
results in 1
due to rounding. I want to help my engineers avoid this.
What is the cleanest way to accomplish this? I tried adding a new file in package kotlin
which works but feels like a code smell.Gunslingor
07/14/2020, 8:51 PMJoel
07/14/2020, 9:01 PMclass SafeDecimal(value: String) : BigDecimal(value, DECIMAL128) {
operator fun plus(other: BigDecimal): BigDecimal = add(other, DECIMAL128)
operator fun minus(other: BigDecimal): BigDecimal = subtract(other, DECIMAL128)
operator fun div(other: BigDecimal): BigDecimal = divide(other, DECIMAL128)
operator fun times(other: BigDecimal): BigDecimal = multiply(other, DECIMAL128)
/**
* Returns the value of this number as a [Byte], which may involve rounding or truncation.
*/
override fun toByte(): Byte {
TODO("Not yet implemented")
}
/**
* Returns the [Char] with the numeric value equal to this number, truncated to 16 bits if appropriate.
*/
override fun toChar(): Char {
TODO("Not yet implemented")
}
/**
* Returns the value of this number as a [Short], which may involve rounding or truncation.
*/
override fun toShort(): Short {
TODO("Not yet implemented")
}
}
These definitions must exist as BigDecimal
implements kotlin.Number
.Gunslingor
07/14/2020, 9:07 PMJoel
07/14/2020, 9:08 PMSafeDecimal.toChar
to match BigDecimal.toChar
Joel
07/14/2020, 9:08 PMBigDecimal
behind the covers and require implementation.Gunslingor
07/14/2020, 9:09 PMGunslingor
07/14/2020, 9:14 PM