Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 337
Bernd Avatar asked Sep 02 '16 22:09

Bernd


1 Answers

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"
like image 135
Leo Dabus Avatar answered Oct 29 '22 08:10

Leo Dabus