Search code examples
iosswiftroundingfoundationmeasurement

How to round a value of type Measurement using MeasurementFormatter in Swift?


I need to round a value of type Measurement<UnitLength> to the nearest Int using MeasurementFormatter. Given the following sample:

let distance = Measurement(value: 0.28, unit: .miles)

let formattedDistance = measurementFormatter.string(from: distance) // "492.8 yd"

What I am trying to achieve is "493 yd" instead of "492.8 yd"

I tried using roundingMode but didn't help with any of its modes:

measurementFormatter.numberFormatter.roundingMode = .up

Any help or idea is appreciated.


Solution

  • You need to set maximumFractionDigits to 0 on the NumberFormatter as well as the roundingMode to .up to force the formatter to round decimal numbers up.

    measurementFormatter.numberFormatter.maximumFractionDigits = 0
    measurementFormatter.numberFormatter.roundingMode = .up