本文介绍了从货币中删除小数位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下示例:

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

I want to have the currency output with 2 digests. In case the currency digests are all zero I want that they will not be displayed. So 3,00 should be displayed as: 3. All other values should be displayed with the two digests.

我该怎么做?

推荐答案

您必须将 numberStyle 设置为 .decimal 样式才能设置 minimumFractionDigits 属性取决于浮点数是否为偶数:

You have to set numberStyle to .decimal style to be able to set minimumFractionDigits property depending if the floating point is even or not:

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


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


You can also extend Formatter and create static formatters to avoid creating the formatters more than once when running your code:

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 testing:

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"

这篇关于从货币中删除小数位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:38