【问题标题】:DecimalFormat precision not working correctlyDecimalFormat 精度无法正常工作
【发布时间】:2017-01-09 10:19:28
【问题描述】:

我想使用 DecimalFormat 将浮点数格式化为给定的精度。我有的是这个

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

假设精度为 2,当我这样做时

formatter.format(20.0f).toFloat()

我得到的输出是20.0f 而不是20.00f

【问题讨论】:

    标签: java kotlin decimalformat


    【解决方案1】:

    您将String 转换回Float,从而丢失了String 的格式。

    相反,只打印format的输出:

    println(formatter.format(20.0f))
    

    如果您想要额外的“f”,请将其放入您的模式中:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-01
      相关资源
      最近更新 更多