https://kotlinlang.org logo
#getting-started
Title
# getting-started
t

Tony Blundell

01/01/2021, 11:01 PM
Hi, quick question about doubles. In Kotlin,
0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 < 0.8
evaluates as true, because the left-hand side is actually 0.79r instead of 0.8. What's the best way of dealing with this? I guess I could convert to a string and back, but that feels a little 'hacky'. Is there a better way?
z

zpearce

01/01/2021, 11:05 PM
If you need accuracy, BigDecimal is the way to go
👍 1
if you're going to stick with floating point, all comparisons should have an error bound
also it's not quite 0.79r or 0.8; neither is exactly representable in floating point
t

Tony Blundell

01/01/2021, 11:33 PM
👍 thanks both
d

Denis Korotchenko

01/02/2021, 10:30 AM
You can also try to use construction like this: if (abs(res-pred) < eps)... where eps is a constant like 10^(-7) etc.
e

elizarov

01/13/2021, 10:07 AM
Highly recommended read: https://floating-point-gui.de/