首页 > 解决方案 > 没有小数位的心率

问题描述

我在 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

谢谢

标签: xcodeapple-watchhealthkit

解决方案


一个简单的解决方案是将整数舍入并显示该整数。

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

推荐阅读