Reputation: 1200
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
Upvotes: 0
Views: 783
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