在我的“健康”应用程序中,它说的距离为0.1公里,但在我的应用程序中,值是0.106。如何将其更改为一个小数?这是我用来获取当前统计信息的代码:

pedometer.queryPedometerData(from: Date().startOfDay, to: Date()) { data, error in
            guard let activityData = data, error == nil else {
                print("There was an error getting the data: \(String(describing: error))")
                return
            }
            print((Double(activityData.distance!.intValue)/Double(1000))) // Print out optional distance in of walking and running in meters. / 1000 to convert from meter to km.
        }

打印给我:0.106

最佳答案

您可以使用Swift Measurement类型转换长度单位,然后使用MeasurementFormatter将其显示给用户:

let number: NSNumber = 106
let measurement = Measurement(value: number.doubleValue, unit: UnitLength.meters).converted(to: .kilometers)

let mf = MeasurementFormatter()
mf.unitOptions = .providedUnit
mf.unitStyle = .medium
mf.numberFormatter.maximumFractionDigits = 1
mf.string(from: measurement)   // "0.1 km"

在您的情况下:
guard let value = activityData.distance?.doubleValue else { return }
let measurement = Measurement(value: value, unit: UnitLength.meters).converted(to: .kilometers)

let mf = MeasurementFormatter()
mf.unitOptions = .providedUnit
mf.unitStyle = .medium
mf.numberFormatter.maximumFractionDigits = 1
mf.string(from: measurement)   // "0.1 km"

10-08 05:28