DecimalFormat precision not working correctly

153 views Asked by At

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

1

There are 1 answers

0
nhaarman On BEST ANSWER

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"
}