问题
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?
回答1:
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"
来源:https://stackoverflow.com/questions/39301360/limit-formatted-measurement-to-2-digits