deci.kt - decimal class for Kotlin without tricks
With Deci you can use operators, it makes formulas easy readable to compare with method calls for BigDecimal
val result = (price * quantity - fee) * 100 / (price * quantity) round 2
You would expect numbers are equal independently on decimal zeros. It is not true with BigDecimal:
println(BigDecimal("1.0") == BigDecimal("1"))
false
You need to use the compareTo
instead of the equals
for BigDecimal.
With Deci it is correct:
println(Deci("1.0") == Deci("1"))
true
BigDecimal keeps the scale of the first argument when dividing
println(BigDecimal("5") / BigDecimal("2"))
2
Deci use high scale - up to 20 decimals for precision or scale which is enough for most real world cases.
println(5.deci / 2.deci)
2.5
println(100000.deci / 3.deci)
33333.33333333333333333333
println(Deci("0.00001") / 3.deci)
0.0000033333333333333333333
BigDecimal use the half-even rounding by default, while Deci - half-up, which is more common
println(BigDecimal("2.5") / BigDecimal("2"))
1.2
println(Deci("2.5") / Deci("2") round 1)
1.3