scala - 具有可变十进制精度的双精度格式
问题描述
我知道在 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
如何实现可变的小数精度?
解决方案
这有效
val number = 1.2345
val decimalPlaces = 2
println(("%." + decimalPlaces + "f").format(number))
隐式调用StringLike
for format
。
推荐阅读
- r - R + rvest + 礼貌用于网络抓取 etsy.com
- xml - Groovy SAP CPI 中的日期比较
- django - 电子邮件中的 Django 重置密码 url 仅在复制和粘贴时有效,而不是单击它
- database - 如何从 Oracle db 中删除尾随 0 和偏移量
- c# - 为什么我们的端点是否异步对消费者来说并不重要?
- angular - 如何使用 RxJS 跳过 observable 的第一个值?
- entity-framework-core - 使用 ASP.NET Core 5 和 Entity Framework Core 创建 API 控制器时出错
- spring-boot - 请求正文必须包含以下参数:'client_id'
- flutter - 在 Flutter 中显示在键盘上方的按钮
- python - Tox 找不到 setup.cfg 文件