我想根据测量值打印字符串,但将其限制为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。我的错在哪里
20.22 mg
0 lb
您需要将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"