3

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

Mohdroid
  • 381
  • 4
  • 9
  • I would say this is already readable. What do you mean by dynamic? – Salem Jan 28 '19 at 13:24
  • Maybe [Andrey Breslavs answer to 'Format in kotlin string template'](https://stackoverflow.com/a/23088000/6202869) is something for you... basically move that formatting into its own extension function... – Roland Jan 28 '19 at 13:30

3 Answers3

5

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
Sam Chen
  • 7,597
  • 2
  • 40
  • 73
3

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!

sunlover3
  • 1,999
  • 1
  • 20
  • 25
0

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))
IMParasharG
  • 1,869
  • 1
  • 15
  • 26