Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format a SKProduct price into a Swift currency string?

If you have code such as this, then p will be "2.99":

let price = 2.99
let p = String(format: "%.2f", price)

However, if you have code like this:

let priceNS: NSDecimalNumber = 2.99
let p2 = String(format: "%.2f", priceNS)

Then p2 is "0.00".

How can you format an NSDecimalNumber into a string like this? (NSDecimalNumber is how the price in an SKProduct is stored)

like image 864
Gruntcakes Avatar asked Oct 03 '17 22:10

Gruntcakes


2 Answers

You should format your product price using NumberFormatter and use your product locale: https://developer.apple.com/documentation/storekit/skproduct/1506094-price

let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .currency 
numberFormatter.locale = someSKProduct.priceLocale
let formattedPrice = numberFormatter.string(from: someSKProduct.price) ?? ""
like image 65
Leo Dabus Avatar answered Oct 17 '22 02:10

Leo Dabus


You can use a NumberFormatter to convert an NSNumber to a String.

let priceNS:NSDecimalNumber = 2.99
let nf = NumberFormatter()
nf.maximumFractionDigits = 2
nf.string(from: priceNS) //2.99
like image 21
Dávid Pásztor Avatar answered Oct 17 '22 02:10

Dávid Pásztor