Saeed Bahari
Saeed Bahari

Reputation: 5

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.

Upvotes: 0

Views: 2956

Answers (2)

Parkinson
Parkinson

Reputation: 71

In my case, i had to get only the exact digits of two numbers after the decimal point. I achieved it by doing this:

val input = 30.47f
val remainder = (input * 100).toInt() - (input.toInt() * 100)
// remainder = 47 exactly, and not 469999999...

Hope this would be helpful for someone.

Upvotes: 0

Alexey Romanov
Alexey Romanov

Reputation: 170815

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/

Upvotes: 2

Related Questions