Remove Decimal places from Currency?

笑着哭i 提交于 2019-12-08 10:47:00

问题


I have the following example:

// Currencies

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

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

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.

How can I do that?


回答1:


You have to set numberStyle to DecimalStyle to be able to set minimumFractionDigits property depending if the double is even or not as follow:

extension Double {
    var formatted: String {
        let numberFormater = NSNumberFormatter()
        numberFormater.locale = NSLocale.currentLocale()
        numberFormater.numberStyle = NSNumberFormatterStyle.DecimalStyle
        numberFormater.maximumFractionDigits = 2
        numberFormater.minimumFractionDigits = self - Double(Int(self)) == 0 ? 0 : 2
        return numberFormater.stringFromNumber(self) ?? ""
    }
}


3.0.formatted    // "3"
3.12.formatted   // "3.12"
3.20.formatted   // "3.20"

var price = 3.20
println("price: \(price.formatted)")

Edit

extension Double {
    var currency: String {
        let numberFormater = NSNumberFormatter()
        numberFormater.locale = NSLocale.currentLocale()
        numberFormater.numberStyle = NSNumberFormatterStyle.CurrencyStyle
        let result = numberFormater.stringFromNumber(self) ?? ""
        return result.hasSuffix(".00") || result.hasSuffix(",00") ? result[result.startIndex..<result.endIndex.predecessor().predecessor().predecessor()] : result
    }

}


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

var price = 3.0
println("price: \(price.currency)")



回答2:


Instead of using NSNumberFormatter you can just use NSString init(format: arguments:)

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

I'm not good with swift, but this should work.

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



来源:https://stackoverflow.com/questions/30947017/remove-decimal-places-from-currency

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!