Tom Harrington Tom Harrington - 21 days ago 5x
iOS Question

Use MeasurementFormatter to display meters as feet

I'm having trouble getting the new

class to give me results in appropriate units. I have values in meters that I want to display in localized strings, either meters or feet depending on the user's locale.

I have this:

let meters : Double = 10
let metersMeasurement = Measurement(value: meters, unit: UnitLength.meters)

let measurementFormatter = MeasurementFormatter()
measurementFormatter.locale = Locale(identifier: "en_US")

let localizedString = measurementFormatter.string(from: metersMeasurement)

This gives me a string of "0.006mi". It's correct, I guess, but converting 10 meters to miles is kind of ridiculous. What I want is "32.8ft".

option on
isn't helpful-- that just gives me a result in meters.

I could look up the current locale and handle this myself, but that's exactly the kind of thing that
is supposed to make unnecessary. Is there some way to get it to do what I need?


You should set the formatter's unitOptions to naturalScale:

let measurementFormatter = MeasurementFormatter()
measurementFormatter.unitOptions = .naturalScale

And you should only set the locale if you want every user in any locale to see the value in the specific locale.