SwiftUI中能否调整.currency格式样式的小数位数?
SwiftUI中自定义货币格式小数位数的解决方案
你不需要局限于.number格式或完全自定义NumberFormatter,在iOS 15+、macOS 12+及以上版本,SwiftUI的FormatStyle原生支持为货币格式指定自定义小数位数,同时也保留自定义Formatter的方案供更复杂场景使用。
方法1:利用FormatStyle的precision修饰(推荐,iOS 15+)
直接在.currency格式后链式调用.precision()方法,指定小数部分的长度(固定位数或范围均可)。比如要保留3位小数,就用.fractionLength(3);如果需要支持3-4位小数,可写成.fractionLength(3...4)。
修改后的示例代码:
import SwiftUI struct SwiftUIView: View { @State private var price = 2.099 // 定义固定3位小数的美元货币格式 private let currencyFormat: FloatingPointFormatStyle<Double>.Currency = .currency(code: "USD") .precision(.fractionLength(3)) var body: some View { TextField("Price", value: $price, format: currencyFormat) Text("\(price, format: currencyFormat)") } }
这样2.099会准确显示为$2.099,不会被四舍五入为两位小数。如需4位小数,只需将.fractionLength(3)改为.fractionLength(4)。
方法2:自定义NumberFormatter(兼容旧版本/复杂场景)
如果需要适配iOS 14及以下版本,或者有更多格式定制需求(比如不同区域的特殊货币规则),可以自定义NumberFormatter:
import SwiftUI struct SwiftUIView: View { @State private var price = 2.099 private var customCurrencyFormatter: NumberFormatter { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.currencyCode = "USD" formatter.minimumFractionDigits = 3 formatter.maximumFractionDigits = 3 // 固定3位,如需4位则改为4,也可设置不同的最小/最大值 return formatter } var body: some View { TextField("Price", value: $price, formatter: customCurrencyFormatter) Text(customCurrencyFormatter.string(from: NSNumber(value: price)) ?? "") } }
综上,你有两种灵活的解决方案,优先选择方法1的原生扩展方案,代码更简洁且贴合SwiftUI的设计风格;若有兼容性或复杂定制需求,再使用自定义NumberFormatter,无需退而使用.number格式。
内容的提问来源于stack exchange,提问作者0x1801ce
相关产品推荐
相关产品推荐

