Bernd Bernd - 3 months ago 42
Swift Question

Limit formatted Measurement to 2 digits

I'd like to print a string based on a Measurement but limit it to 2 digits. I am using the MeasurementFormatter for this.

var beans:Measurement = Measurement(value: 20.22321, unit: UnitMass.milligrams) // "20.22321 mg"
let formatter = MeasurementFormatter()
formatter.numberFormatter.maximumFractionDigits = 2
let label = formatter.string(from: beans) // 0 lb


I expected
20.22 mg
as a results, not
0 lb
. Where's my mistake?

Answer

You need to set the MeasurementFormatter property unitOption to .providedUnit

let beans = Measurement(value: 20.22321, unit: UnitMass.milligrams) // "20.22321 mg"
let formatter = MeasurementFormatter()
formatter.unitOptions = .providedUnit
formatter.numberFormatter.maximumFractionDigits = 2
let label = formatter.string(from: beans) // "20.22 mg"
Comments