DecimalFormat精度无法正常工作
我想格式化使用DecimalFormat给定的精度的浮动。 我拥有的是这个
val formatter = DecimalFormat(if (precision > 0) "#0.${"0".repeat(precision)}" else "#")
可以说,精度是2,当我这样做
formatter.format(20.0f).toFloat()
我得到的输出为20.0f
而不是20.00f
您将String
转换回Float
,从而失去了String
的格式。
相反,只需打印format
的输出:
println(formatter.format(20.0f))
如果你想额外的'f',把它放在你的模式:
val pattern = if (precision > 0) { "#0.${"0".repeat(precision)}f" } else { "#f" }