我编写了简单的代码将温度单位从开氏温度转换为华氏温度或摄氏温度。
我想删除小数点,例如71.5999999999957结果。
您有任何简单的解决方案吗?
import Foundation
var base: Double = 295.14999999999998
let kelvinTemperature = Measurement.init(value: base, unit: UnitTemperature.kelvin)
let fahrenheitTemperature = kelvinTemperature.converted(to: .fahrenheit)
let celsiusTemperature = kelvinTemperature.converted(to: .celsius)
print(celsiusTemperature)
print(fahrenheitTemperature)
结果:
22.0°C
71.5999999999957°F
答案 0 :(得分:1)
我找到了解决方法。
import Foundation
var base: Double = 295.14999999999998
let kelvinTemperature = Measurement.init(value: base, unit: UnitTemperature.kelvin)
let fahrenheitTemperature = kelvinTemperature.converted(to: .fahrenheit)
let celsiusTemperature = kelvinTemperature.converted(to: .celsius)
let numFormatter = NumberFormatter()
numFormatter.maximumFractionDigits = 2
let measureFormatter = MeasurementFormatter()
measureFormatter.numberFormatter = numFormatter
let fahrenheit = measureFormatter.string(from: fahrenheitTemperature)
print(celsiusTemperature)
print(fahrenheit)