Search code examples
iosswiftuicollectionviewswift3number-formatting

Formatting with 2 decimal places (NSDecimalNumber)


I have an extension in my NSDecimalNumber

extension NSDecimalNumber {
    func format(f: String) -> String {
        return String(format: "%\(f)f", self)
    }
}

This should allow me to do the following:

var price = 34.2499999

price.format(f: ".2") // 35.25

Instead, I get 0.00 in my UICollectionViewCell:

func configureCell(_ item: Item) {

        self. item = item

        nameLabel.adjustsFontSizeToFitWidth = true
        priceLabel.adjustsFontSizeToFitWidth = true
        nameLabel.text = self. item.name.capitalized
        priceLabel.text = "£\(self. item.price!.format(f: ".2"))"

    }

I would like to format it with the real price showing two decimal places instead of a random number. All prices are retrieved from a database and are accurate with only 2 decimal places.

For some reason, when I remove the formatting from the extension, I get more decimals where I only have 2 in the database. Why is this happening and how is it solved?


Solution

  • It's probably due a type conversion under the hood. You can always format the price with a NSNumberFormatter to give you the correct currency format instead of doing a string format like so

    extension NSNumber {
        func toCurrency() -> String? {
            let numberFormatter = NumberFormatter()
            numberFormatter.numberStyle = .currency
            return numberFormatter.string(from: self)
        }
    }
    

    Also remember to initialize a NSDecimalNumber with your price variable before calling this extension method