Core Motion将距离转换为KM

问题描述 投票:2回答:2

在我的健康应用程序中它表示距离0,1km,但在我的应用程序中它给我的值0.106。如何将其更改为一个desimal?这是我用来获取当前统计数据的代码:

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

ios swift core-motion
2个回答
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"

0
投票

就像是:

let dist = Double(activityData.distance!.intValue)/Double(1000)
let str = String(format: @"%.1f", "", dist)
print(str)
© www.soinside.com 2019 - 2024. All rights reserved.