6

I'm trying to get the localised unit symbol for any measurement obtained using a measurement formatter.

For example, if the locale uses degrees Fahrenheit, but the app stores it's data in Celsius, I would create a measurement formatter as follows:

let formatter = MeasurementFormatter()
let measurement = Measurement(value: 10, unit: UnitTemperature.celsius)
formatter.string(from: measurement)

This last line will give me "50°F". Now I want to get the "°F" value from the measurement.

I have tried using

formatter.string(from: measurement.unit)

But this just gives me "deg. C"

Thanks in advance!

Danny Bravo
  • 4,534
  • 1
  • 25
  • 43

4 Answers4

2

You probably just have to set the locale of the formatter like this:

formatter.locale = Locale(identifier: "en-US")

Or if you want to get the current locale of the device and set it from that do like this:

formatter.locale = Locale.current

and then

formatter.string(from: measurement.unit)
Lars Christoffersen
  • 1,719
  • 13
  • 24
  • 2
    this **does not work** since it returns the localized provided unit, which is Celsius and not Farenheit. Note that even in en-US, localized celsius is celsius... the unit will not change unless it is converted first. – Daniel Mar 02 '21 at 12:44
1

A bit late to the party, building on Lars answer and Daniel's comment, the following code allows you to get a localized unit and value:

let measurement = Measurement<UnitTemperature>(value: 10, unit: .celsius)
let formatter = MeasurementFormatter()

let localMeasurement = measurement.converted(to: UnitSpeed(forLocale: .autoupdatingCurrent))

let unit = formatter.string(from: localMeasurement.unit)
let value = localMeasurement.value //.rounded()
lewis
  • 2,936
  • 2
  • 37
  • 72
-1

With my Mac pref set to en_US with the temperature in Fahrenheit, the following code gives me what you want in Objective-C:

NSUnitTemperature * fahrenheit = [NSUnitTemperature fahrenheit];
NSMeasurement * measurement = [[NSMeasurement alloc] initWithDoubleValue:35 unit:fahrenheit];
NSMeasurementFormatter * formatter = [[NSMeasurementFormatter alloc] init];

NSLog(@"%@", measurement.unit.symbol); // °F

This output: °F

martinjack
  • 51
  • 6
-4

In order to get the "°F", I think that you must set the locale of the formatter to "en_US".

martinjack
  • 51
  • 6