Search code examples
iosswift3nsmeasurementformattermeasurementformatter

Use MeasurementFormatter to display meters as feet


I'm having trouble getting the new MeasurementFormatter 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".

The .providedUnit option on MeasurementFormatter 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 MeasurementFormatter is supposed to make unnecessary. Is there some way to get it to do what I need?


Solution

  • 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.