DEV Community

Shawn Baek
Shawn Baek

Posted on • Updated on

How to display the temperature with a unit?

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)
Enter fullscreen mode Exit fullscreen mode

UnitStyle

//70 degrees Fahrenheit
measureFormatter.unitStyle = .long
//70°F
measureFormatter.unitStyle = .medium
//70°
measureFormatter.unitStyle = .short
Enter fullscreen mode Exit fullscreen mode

The default unitStyle is medium. You can set the three different unitStyle.

Results

Apple Weather App
The unitStyle is short.

If you want to see more postings, visit my blog. https://shawnbaek.com

Top comments (3)

Collapse
 
efpage profile image
Eckehard

Hy,

can you be a bit more specific? We should at least know the programming language you are asking for.

Collapse
 
shawnbaek profile image
Shawn Baek

@efpage Hey Thanks for your comments. I updated my content. If you like my post could you subscribe to my blog? :)

Collapse
 
efpage profile image
Eckehard

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