Search code examples
iosswiftnsdate

Remove Decimal places from Currency?


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?


Solution

  • 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"