Disclaimer: this question asks and accepts an answer to a very unusual use-case.
This is the most popular Kotlin question on rounding, but the use case is not explained and the solution is not generalizable. For answers to common questions on rounding in Kotlin:
- "How would I round to n decimal places in Kotlin?" see Gaurang Goda's answer.
- "How do I round a decimal up?" see hotkey's answer
Original question below:
I have a Double variable that is 0.0449999
and I would like to round it to 1 decimal place 0.1
.
I am using Kotlin but the Java solution is also helpful.
val number:Double = 0.0449999
I tried getting 1 decimal place with these two solutions:
val solution = Math.round(number * 10.0) / 10.0
val solution = String.format("%.1f", number)
The problem is that I get 0.0 in both cases because it rounds the number from 0.04
to 0.0
. It doesn't take all decimals and round it.
I would like to obtain 0.1: 0.045 -> 0.05 -> 0.1
Disclaimer: This answer solves a very unusual use case and should not be used as a generalized solution to rounding in Kotlin.
Finally I did what Andy Turner
suggested, rounded to 3 decimals, then to 2 and then to 1:
Answer 1:
val number:Double = 0.0449999
val number3digits:Double = String.format("%.3f", number).toDouble()
val number2digits:Double = String.format("%.2f", number3digits).toDouble()
val solution:Double = String.format("%.1f", number2digits).toDouble()
Answer 2:
val number:Double = 0.0449999
val number3digits:Double = Math.round(number * 1000.0) / 1000.0
val number2digits:Double = Math.round(number3digits * 100.0) / 100.0
val solution:Double = Math.round(number2digits * 10.0) / 10.0
Result:
0.045 → 0.05 → 0.1
Note: I know it is not how it should work but sometimes you need to round up taking into account all decimals for some special cases so maybe someone finds this useful.