In this post, I’ll share how to display the temperature with the unit using the MeasurementFormatter.
MeasurementFormatter
let numFormatter = NumberFormatter()
numFormatter.maximumFractionDigits = 0
let measureFormatter = MeasurementFormatter()
measureFormatter.numberFormatter = numFormatter
let kelvin: Double = 294
var temperature: String = ""
let kelvinTemperature = Measurement(
value: kelvin,
unit: UnitTemperature.kelvin
)
//temperature is automatically changed the celcius / farenheit depending on locale.
temperature = measureFormatter.string(from: kelvinTemperature)
//70°F
print(temperature)
UnitStyle
//70 degrees Fahrenheit
measureFormatter.unitStyle = .long
//70°F
measureFormatter.unitStyle = .medium
//70°
measureFormatter.unitStyle = .short
The default unitStyle is medium. You can set the three different unitStyle.
Apple Weather App
The unitStyle is short.
If you want to see more postings, visit my blog. https://shawnbaek.com
Top comments (3)
Hy,
can you be a bit more specific? We should at least know the programming language you are asking for.
@efpage Hey Thanks for your comments. I updated my content. If you like my post could you subscribe to my blog? :)
Hy Shawn,
I´m still a bit confused about the platform you are working on. Seems to be something apple specific, maybe Swift?
BR, Eckehard