Is it possible to use a method or something else rather â%.6fâ.format(value) in order to achieve the same thing? this is my code :
println("%.6f".format(value))
I'll want to make it more dynamic and readable
Is it possible to use a method or something else rather â%.6fâ.format(value) in order to achieve the same thing? this is my code :
println("%.6f".format(value))
I'll want to make it more dynamic and readable
You can make it an Extension Function for your project, which is a very powerful feature of Kotlin, the function is like this:
fun Double.roundDecimal(digit: Int) = "%.${digit}f".format(this)
Just put it in a Kotlin file But Outside The Class, then you can access it everywhere in your project:
fun main() {
val number = 0.49555
println(number.roundDecimal(2))
println(number.roundDecimal(3))
}
Output:
0.50
0.496
You can always use
String.format("%.6f", value)
But you can extract the format in a variable
val FORMAT_FLOAT = "%.6f"
println(String.format(FORMAT_FLOAT, value))
It depends on your preferences. Good luck!
you can use DecimalFormat
class to round a given number. More info
i.e.
val num = 1.345672
val df = DecimalFormat("#.######")
df.roundingMode = RoundingMode.CEILING
println(df.format(num))