How to properly format currency on ios

Viewed 47907

I'm looking for a way to format a string into currency without using the TextField hack.

For example, i'd like to have the number "521242" converted into "5,212.42" Or if I have a number under 1$, I would like it to look like this: "52" -> "0.52"

Thanks

8 Answers

One thing about using formatters is they are expensive to create. It is best to create them once per view or viewController. Using lazy is the perfect solution for avoiding this overhead. This also moves a lot of boilerplate up out of the way of your main code.

class MyViewController: UIViewController {
    @IBOutlet var priceLabel: UILabel!

    private lazy var currencyFormatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.currencySymbol = "$"
        formatter.numberStyle = .currency
        return formatter
    }()

     // rest of class
 }

To use it, as noted elsewhere it is best to use Decimal for currency, Double is an approximation.

priceLabel.text = currencyFormatter.string(for: Decimal(9.48))

Output:

$9.48
Related