我正在用Xcode开发Apple Watch的手表应用,Apple Developer网站SpeedySloth: Creating a Workout的示例代码将HeartRate舍入到小数点后一位,例如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