-3

Im doing a watch app for the Apple Watch in Xcode and the sample code from the Apple Developer site SpeedySloth: Creating a Workout has the HeartRate rounded to one decimal place, e.g. 61.0 How can I fix this?

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")

I tried changing both the 1's in there to 0 but that gave me a 6.1 BPM or a 0.0 BPM

Thanks

Kurt L.
  • 623
  • 10
  • 23

1 Answers1

2

A simple solution is to round to an integer and show the integer.

let value = // ... some Double ...
let s = String(Int(value.rounded(.toNearestOrAwayFromZero)))
label.setText(s + " BPM")

Properly, however, you should put formatting a string based on a number into the hands of a NumberFormatter. That's its job: to format a number.

let i = value.rounded(.toNearestOrAwayFromZero)
let nf = NumberFormatter()
nf.numberStyle = .none
let s = nf.string(from: i as NSNumber)!
// ... and now show the string
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Thanks, I did this and it worked. Im probably adding stuff I shouldn't but its working `let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute()) let value = statistics.mostRecentQuantity()?.doubleValue(for: heartRateUnit) let roundedValue = Double( round( 1 * value! ) / 1 ) let valueA = roundedValue let s = String(Int(valueA.rounded(.toNearestOrAwayFromZero))) label.setText(s + " BPM")` – Kurt L. Oct 19 '19 at 03:11