我想根据测量值打印一个字符串,但将其限制为2位数。我正在使用 MeasurementFormatter 。
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
我希望20.22 mg
作为结果,而不是0 lb
。哪里是我的错?
答案 0 :(得分:4)
您需要将MeasurementFormatter属性unitOption设置为.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"