So, I’m debugging my code, and I found a weird bug(?) in Kotlin. I don’t know if this is intended, but from the code examples I saw online, this is not supposed to be the case.
unrounded: 1664.5
rounded: 1664.0 ← round(): double
expected: 1665.0
So, I’m debugging my code, and I found a weird bug(?) in Kotlin. I don’t know if this is intended, but from the code examples I saw online, this is not supposed to be the case.
unrounded: 1664.5
rounded: 1664.0 ← round(): double
expected: 1665.0
From the Kotlin round
documentation:
Rounds the given value x towards the closest integer with ties rounded towards even integer.
I found the answer thanks to this Reddit discussion. Sending it here for others.
https://www.reddit.com/r/Kotlin/comments/881f7u/strange_behavior_of_kotlinmathround/
round(): float
and round(): double
does not work like Math.round() in Java.
Instead, use .roundToInt(): Int
or .roundToLong(): Long
Thank you. I found the answer. I found it weird because it’s inconsistent with Java’s Math.round()
.roundToInt()
works like Java’s Math.round()