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
You're converting the
String
back toFloat
, thereby losing the format theString
was in.Instead, just print the output of
format
:If you want the extra 'f', put it in your pattern: