kev
kev

Reputation: 1200

How to multiply Doubles without losing precision?

Given this function:

fun  multiplyByHundred(num:Double):Double{
    return num * 100
}

These are results for some inputs:

69.56 => 6956.0

69.57 => 6956.999999999999

69.58 => 6958.0

69.59 => 6959.0

  1. Why does 69.57 result in 6956.999999999999?
  2. How do I correctly do this calculation without losing precision and make it work with any Double?

Upvotes: 0

Views: 783

Answers (1)

Bathsheba
Bathsheba

Reputation: 234795

You can't. A double can represent only a sparse subset of the real numbers. You might get away with using a double if you can format the output appropriately (which is essentially what Microsoft Excel does, along with some very clever tricks for expressions like 1/3 + 1/3 + 1/3).

If you need perfect precision then use a type capable of doing that. The decimal type BigDecimal is probably what you want.

If you're working with money, and don't need to worry about currencies that have 1000s (e.g. Tunisian Dinar) or bitcoin (8 decimal places), then working in cents and using integers is one approach.

Upvotes: 3

Related Questions