首页 > 解决方案 > 具有可变十进制精度的双精度格式

问题描述

我知道在 Scala.js 中(不能使用java.text.DecimalFormat)我可以这样写:

val number = 1.2345
println(f"$x%.2f") // "1.23"

但是,这似乎不起作用:

val decimalPlaces = 2
println(f"$x%.${decimalPlaces}f")
// [error] Missing conversion operator in '%'; use %% for literal %, %n for newline      f"$x%.${decimalPlaces}f"

// also doesn't work: (f"$x%." + decimalPlaces + "f").toFloat

如何实现可变的小数精度?

标签: scalascala.js

解决方案


这有效

val number = 1.2345
val decimalPlaces = 2
println(("%." + decimalPlaces + "f").format(number))

隐式调用StringLikefor format


推荐阅读