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?
You need to set the MeasurementFormatter
property unitOptions
to .providedUnit
:
let beans = Measurement<UnitMass>(value: 20.22321, unit: .milligrams) // "20.22321 mg"
let formatter = MeasurementFormatter()
formatter.unitOptions = .providedUnit
formatter.numberFormatter.maximumFractionDigits = 2
let label = formatter.string(from: beans) // "20.22 mg"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With