我的下面的功能偶尔会产生一个无穷大的数字。我以为我可以使用下面的舍入函数来避免使用无限数...换句话说1.333333333333(INF)四舍五入到1.33,但编译器仍将INF.rounded的结果视为无限,我怎么能舍入所以我仍然可以在这里推出一个值?特别是我正在尝试编码为JSON并收到此错误:
metadata ERROR = invalidValue(inf, Swift.EncodingError.Context(codingPath: [Watch_Extension.HockeyTrackerMetadata.(CodingKeys in _B2A7010AF20490DAF638D1E0A01E4982).maximumCapableSpeed], debugDescription: "Unable to encode Double.infinity directly in JSON. Use JSONEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded.", underlyingError: nil))
//Calculation
func calculateMaximumAndAverageSkatingEfficiency() {
let heartRateUnit:HKUnit = HKUnit(from: "count/min")
let heartRatesAsDouble = heartRateValues.map { $0.quantity.doubleValue(for: heartRateUnit)}
let maxHeartRate = heartRatesAsDouble.max()
guard let maxHeartRateUnwrapped = maxHeartRate else { return }
maximumEfficiencyFactor = ((1760.0 * (maxSpeed / 60)) / maxHeartRateUnwrapped).round(to: 2)
guard let averageIceTimeHeartRateUnwrapped = averageIceTimeHeartRate else { return }
averageEfficiencyFactor = ((1760.0 * (averageSpeed / 60)) / averageIceTimeHeartRateUnwrapped).round(to: 2)
}
//Round extension I am using
extension Double {
func round(to places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return Darwin.round(self * divisor) / divisor
}
}
//Usage
if let averageEfficiencyFactorUnwrapped = averageEfficiencyFactor {
metadata.averageEfficiencyFactor = averageEfficiencyFactorUnwrapped.round(to: 2)
}
答案 0 :(得分:1)
"无限的价值"意味着该值为正或负无穷大,可能是因为它是零除或类似数学运算的结果。这并不意味着该值是非终止小数。
确保maxHeartRateUnwrapped
和averageIceTimeHeartRateUnwrapped
不为零。