Matt Groth
Matt Groth

Reputation: 33

How to get accurate remainder for doubles?

According to the comment description for Double.rem:

    /**
     * Calculates the remainder of truncating division of this value by the other value.
     * 
     * The result is either zero or has the same sign as the _dividend_ and has the absolute value less than the absolute value of the divisor.
     */
    @SinceKotlin("1.1")
    public operator fun rem(other: Double): Double

However, when I run the following code:

fun main() {
    println(10.0 % 0.2)
}

It outputs 0.19999999999999946 when it should output 0.0. How do I run an accurate rem for doubles?

Note: try it yourself here

Upvotes: 1

Views: 887

Answers (1)

broot
broot

Reputation: 28412

Floats and doubles are by design imprecise. They can only hold and calculate approximations of values.

If you need precision similar to regular ints and use them with fractions, you can use BigDecimal:

BigDecimal("10.0") % BigDecimal("0.2")

Just note it is sometimes more complicated and you need to understand their properties like: scale, rounding mode, etc. For your case I believe above code should be sufficient.

Upvotes: 4

Related Questions