Sagar
Sagar

Reputation: 405

DecimalFormat precision not working correctly

I would like to format a float using to a given precision using DecimalFormat. What I have is this

val formatter = DecimalFormat(if (precision > 0) "#0.${"0".repeat(precision)}" else "#")

Lets say the precision is 2 and when I do

formatter.format(20.0f).toFloat()

I get the output as 20.0f and not 20.00f

Upvotes: 0

Views: 161

Answers (1)

nhaarman
nhaarman

Reputation: 100358

You're converting the String back to Float, thereby losing the format the String was in.

Instead, just print the output of format:

println(formatter.format(20.0f))

If you want the extra 'f', put it in your pattern:

val pattern = if (precision > 0) {
    "#0.${"0".repeat(precision)}f"
} else {
    "#f"
}

Upvotes: 2

Related Questions