Today I tried to get the decimal of a float. Parti...
# mathematics
s
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
s
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
You don’t have use strings, though. You can do:
round((value - value.toInt()) * 100) / 100
.
s
It works like a charm after adding
f
at the very end. Thanks a lot!
Copy code
round((value - value.toInt())*100)/100f