简体   繁体   中英

How can I get the localised Unit Symbol from a MeasurementFormatter result?

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!

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)

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()

为了获得“°F”,我认为您必须将格式化程序的语言环境设置为“ en_US”。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM