从货币中删除小数位?

Remove Decimal places from Currency?

我有以下示例:

// 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。所有其他值应与两个摘要一起显示。

我该怎么做?

除了使用 NSNumberFormatter,你还可以使用 NSString init(format: arguments:)

var string = NSString(format:@"%.2g" arguments:price)

我不擅长 swift,但这应该行得通。

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265

您必须将 numberStyle 设置为 .decimal 样式才能设置 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) ?? ""
    }
}

游乐场测试:

3.0.currencyFormatted            // ""
3.12.currencyFormatted           // ".12"
3.2.currencyFormatted            // ".20"

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

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