gpt4 book ai didi

ios - 从货币中删除小数位?

转载 作者:行者123 更新时间:2023-11-29 01:55:13 25 4
gpt4 key购买 nike

我有以下示例:

// Currencies

var price: Double = 3.20
println("price: \(price)")

let numberFormater = NSNumberFormatter()
numberFormater.locale = locale
numberFormater.numberStyle = NSNumberFormatterStyle.CurrencyStyle
numberFormater.maximumFractionDigits = 2

我想要有 2 个摘要的货币输出。如果货币摘要全部为零,我希望它们不会显示。所以 3,00 应该显示为:3。所有其他值应与两个摘要一起显示。

我该怎么做?

最佳答案

您必须将 numberStyle 设置为 .decimal 样式才能根据 float 是否为偶数设置 minimumFractionDigits 属性:

extension FloatingPoint {
var isWholeNumber: Bool { isZero ? true : !isNormal ? false : self == rounded() }
}

您还可以扩展 Formatter 并创建静态格式化程序,以避免在运行代码时多次创建格式化程序:

extension Formatter {
static let currency: NumberFormatter = {
let numberFormater = NumberFormatter()
numberFormater.numberStyle = .currency
return numberFormater
}()
static let currencyNoSymbol: NumberFormatter = {
let numberFormater = NumberFormatter()
numberFormater.numberStyle = .currency
numberFormater.currencySymbol = ""
return numberFormater
}()
}

extension FloatingPoint {
var currencyFormatted: String {
Formatter.currency.minimumFractionDigits = isWholeNumber ? 0 : 2
return Formatter.currency.string(for: self) ?? ""
}
var currencyNoSymbolFormatted: String {
Formatter.currencyNoSymbol.minimumFractionDigits = isWholeNumber ? 0 : 2
return Formatter.currencyNoSymbol.string(for: self) ?? ""
}
}

Playground 测试:

3.0.currencyFormatted            // "$3"
3.12.currencyFormatted // "$3.12"
3.2.currencyFormatted // "$3.20"

3.0.currencyNoSymbolFormatted // "3"
3.12.currencyNoSymbolFormatted // "3.12"
3.2.currencyNoSymbolFormatted // "3.20"

let price = 3.2
print("price: \(price.currencyFormatted)") // "price: $3.20\n"

关于ios - 从货币中删除小数位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30947017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com