Search code examples
kotlinfloating-pointoperatorsprecision

kotlin rem operator doesn't give me correct answer


I use remainder inside my code with kotlin in android project but with this value I don't get the correct answer.

variable is :

 val vv = 1529.71
 val ratio = 0.01
 val remainder = vv.rem(ratio)

it's must be zero but remainder value is : 4.5363018896793506E-15

I don't understand why this happened.


Solution

  • The answer is because vv isn't actually 1529.71 but the closest possible Double, the exact value is 1529.7100000000000363797880709171295166015625 (the easiest way to see it is println(java.math.BigDecimal(vv))). If you want to represent decimal numbers exactly, use BigDecimal and pass the fraction as a string:

    val vv = BigDecimal("1529.71")
    val ratio = BigDecimal("0.01")
    val remainder = vv.rem(ratio)
    

    Read more about floating point here: https://floating-point-gui.de/