一尘不染

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

swift

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


阅读 272

收藏
2020-07-07

共1个答案

一尘不染

您需要将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"
2020-07-07