https://kotlinlang.org logo
#mathematics
Title
# mathematics
s

Simon Schubert

10/21/2019, 4:30 PM
Today I tried to get the decimal of a float. Particularly I want to check if the decimal is
33
or
66
. So I wrote a function like
value - value.toInt()
which returns e.g.
0.33f
. I thought it works fine. But today I noticed that for some values it doesn’t work. For example:
8.33 returns 0.32999992
. I assume it's already a known bug? Anyway I found that very odd. Whats an efficient workaround?
Copy code
for(i in 0..8) {
    println("${8.33f - i}")
}
returns
Copy code
8.33
7.33
6.33
5.33
4.33
3.33
2.33
1.3299999
0.32999992
1.3.50 jvm
e

elizarov

10/21/2019, 4:43 PM
s

Simon Schubert

10/21/2019, 6:05 PM
I didn't know that the floating point issues happen at that absurdly simple code. Sorry for questioning the kotlin language 😬 I ended up with
Copy code
"%.2f".format(value - value.toInt())
👍 1
e

elizarov

10/22/2019, 7:37 AM
You don’t have use strings, though. You can do:
round((value - value.toInt()) * 100) / 100
.
s

Simon Schubert

10/22/2019, 9:53 AM
It works like a charm after adding
f
at the very end. Thanks a lot!
Copy code
round((value - value.toInt())*100)/100f
6 Views