You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何避免货币值自动取整?

在Swift中避免货币值自动取整的解决方案

你的问题核心在于NumberFormatter默认的舍入规则:71.99除以6的实际结果是11.998333...,默认的.halfUp舍入模式会把这个数四舍五入到两位小数的12.00。要得到$11.99,需要修改格式化器的舍入逻辑,让它直接截断多余小数位而非进位。

修改后的代码

let halfYearlyPrice = 71.99
var perMonthPrice = halfYearlyPrice / 6.0

let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
currencyFormatter.locale = Locale(identifier: "en-US")
// 设置舍入模式为向下截断(舍弃多余小数)
currencyFormatter.roundingMode = .down
// 强制显示两位小数,保证货币格式规范
currencyFormatter.minimumFractionDigits = 2
currencyFormatter.maximumFractionDigits = 2

if let formattedPrice = currencyFormatter.string(from: perMonthPrice as NSNumber) {
    print("formattedPrice: ", formattedPrice)
    print("\(formattedPrice) / month")
}

运行结果

formattedPrice:  $11.99
$11.99 / month

关键说明

  • roundingMode = .down:针对正数场景,该模式会直接舍弃两位小数之后的所有数字,不会触发进位。如果需要处理负数,可根据需求选择.floor(正数场景下两者效果一致)。
  • 显式设置minimumFractionDigits和maximumFractionDigits为2,确保格式化后的货币始终保持两位小数的规范格式,避免出现$12这类不完整的显示。

内容的提问来源于stack exchange,提问作者Mahendra Liya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 14:35:27