Rounding Double to 1 decimal place in Kotlin: how to get 0.1 from 0.044999?
Hello everyone! I just started learning Kotlin for Android and encountered a strange problem with floating-point number rounding.
I have a variable of type Double: `val number = 0.044999`. I need to round it to one decimal place to get 0.1 (that is, mathematically correct rounding up, since the next digit after 0.0 is 4, but if you look at the whole number, 0.045 already gives 0.1 when rounded to one decimal place).
I tried using `String.format("%.1f", number)`, but it outputs `0.0`, because format only looks at the first decimal place? Then I tried `Math.round(number * 10.0) / 10.0`, but the result is again `0.0`. I'm stuck!
Here's my code:
```kotlin
fun main() {
val number = 0.044999
val rounded = Math.round(number * 10.0) / 10.0
println(rounded) // Output: 0.0
}
```
How can I get 0.1? Maybe I'm misunderstanding how rounding works in Kotlin/Java? Or is there a special function for this? Please help!
No answers yet.
Log in to leave an answer
Blogs