Skip to content

labai/deci

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

deci

deci.kt

deci.kt - decimal class for Kotlin without tricks

Math in code

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

BigDecimal vs Deci examples

1. Equals

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

2. Dividing

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

3. Rounding

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

About

deci - decimals w/o tricks

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published