Core Motion将距离转换为KM

时间:2018-12-02 13:33:15

标签: ios swift core-motion

在我的“健康”应用程序中,它说的距离为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

2 个答案:

答案 0 :(得分:1)

您可以使用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"

答案 1 :(得分:0)

类似的东西:

let dist = Double(activityData.distance!.intValue)/Double(1000)
let str = String(format: @"%.1f", "", dist)
print(str)