xcode - 没有小数位的心率
问题描述
我在 Xcode 中为 Apple Watch 做一个手表应用程序以及来自 Apple 开发者网站SpeedySloth 的示例代码:创建锻炼将心率四舍五入到小数点后一位,例如 61.0 我该如何解决这个问题?
case HKQuantityType.quantityType(forIdentifier: .heartRate):
/// - Tag: SetLabel
let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute())
let value = statistics.mostRecentQuantity()?.doubleValue(for: heartRateUnit)
let roundedValue = Double( round( 1 * value! ) / 1 )
label.setText("\(roundedValue) BPM")
我尝试将其中的 1 都更改为 0,但这给了我 6.1 BPM 或 0.0 BPM
谢谢
解决方案
一个简单的解决方案是将整数舍入并显示该整数。
let value = // ... some Double ...
let s = String(Int(value.rounded(.toNearestOrAwayFromZero)))
label.setText(s + " BPM")
但是,正确地,您应该将基于数字的字符串格式化交给 NumberFormatter。这就是它的工作:格式化一个数字。
let i = value.rounded(.toNearestOrAwayFromZero)
let nf = NumberFormatter()
nf.numberStyle = .none
let s = nf.string(from: i as NSNumber)!
// ... and now show the string
推荐阅读
- graphql - graphql 请求适用于 Chrome,但会在 IE11 上中止?
- go - 来自外部包的 AWS Lambda golang 日志记录
- python - 嵌套 if/elif 语句产生奇怪的结果
- delphi - 升级 TeeChart 2015 到 TeeChart 2017 的问题
- node.js - 如何在 kafka-node 中设置 max.poll.records?
- javascript - 使数据表表头选择选项依赖于另一个表头选择输入
- spring - 在名为“mvcValidator”的 bean 上调用销毁方法“close”失败
- java - 显示对话框时应用程序崩溃
- php - 如何使用一个查询而不是多个查询
- git - 剪切后连接 git 历史记录