如何让Measurement将2.5lb显示为2lb 8oz而非小数磅格式?
实现Measurement的复合单位格式化(磅转磅+盎司)
可以依托Measurement本身的单位转换能力,结合简单的数值拆分来实现需求,无需额外辅助类。以下是具体实现方案:
核心实现:将磅转换为“磅+盎司”格式
针对2.5磅转成2 lb 8 oz的场景,我们可以先提取整数磅数,再将剩余的磅值转换为盎司:
let poundsMeasurement = Measurement(value: 2.5, unit: UnitMass.pounds) // 提取整数部分的磅数 let wholePounds = Int(poundsMeasurement.value) // 计算剩余磅值并转换为盎司 let remainingPounds = poundsMeasurement.value - Double(wholePounds) let ouncesMeasurement = Measurement(value: remainingPounds, unit: UnitMass.pounds) .converted(to: .ounces) .rounded() // 确保盎司数为整数 // 组合成目标格式 let formattedResult = "\(wholePounds) lb \(Int(ouncesMeasurement.value)) oz" print(formattedResult) // 输出:2 lb 8 oz
扩展为通用方法,支持多种单位(lb、kg、ea)
针对你数据库存储的三种单位,可以封装一个通用格式化函数,根据单位类型做不同处理:
func formatStoredMeasurement(value: Double, unitType: String) -> String { switch unitType { case "lb": let measurement = Measurement(value: value, unit: UnitMass.pounds) let wholePounds = Int(measurement.value) let remainingPounds = measurement.value - Double(wholePounds) let ounces = Measurement(value: remainingPounds, unit: UnitMass.pounds) .converted(to: .ounces) .rounded() return "\(wholePounds) lb \(Int(ounces)) oz" case "kg": // 可选:也可以将千克转换为“千克+克”格式,或直接用默认格式化 let measurement = Measurement(value: value, unit: UnitMass.kilograms) let formatter = MeasurementFormatter() formatter.unitStyle = .medium return formatter.string(from: measurement) // 如果需要“kg+g”格式,参考磅的逻辑: // let wholeKg = Int(measurement.value) // let remainingKg = measurement.value - Double(wholeKg) // let grams = Measurement(value: remainingKg, unit: UnitMass.kilograms).converted(to: .grams).rounded() // return "\(wholeKg) kg \(Int(grams)) g" case "ea": // 计数单位直接返回数值+单位 return "\(value) ea" default: return "\(value) \(unitType)" } } // 使用示例 print(formatStoredMeasurement(value: 2.5, unitType: "lb")) // 2 lb 8 oz print(formatStoredMeasurement(value: 1.3, unitType: "kg")) // 1.3 kg(或1 kg 300 g,取决于注释内的实现) print(formatStoredMeasurement(value: 5.0, unitType: "ea")) // 5.0 ea
说明
上述实现完全依赖Measurement的单位转换能力,仅做了必要的数值拆分与格式化拼接,没有引入额外的辅助类,符合你“尽可能多地使用Measurement完成”的要求。
内容的提问来源于stack exchange,提问作者fs_tigre
相关产品推荐
相关产品推荐

