Limit formatted Measurement to 2 digits

喜欢而已 提交于 2019-12-17 14:22:08

问题


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?


回答1:


You need to set the MeasurementFormatter property unitOption to .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"


来源:https://stackoverflow.com/questions/39301360/limit-formatted-measurement-to-2-digits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!