Mohdroid
Mohdroid

Reputation: 411

Decimal format in kotlin

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

Upvotes: 3

Views: 8398

Answers (3)

Sam Chen
Sam Chen

Reputation: 8917

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

Upvotes: 5

sunlover3
sunlover3

Reputation: 2049

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!

Upvotes: 3

IMParasharG
IMParasharG

Reputation: 1905

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))

Upvotes: 0

Related Questions