将格式化测量限制为2位数

时间:2016-09-02 22:17:16

标签: ios swift measurement

我想根据测量值打印一个字符串,但将其限制为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。哪里是我的错?

1 个答案:

答案 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"