Reputation: 37600
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)
Upvotes: 6
Views: 3331
Reputation: 236558
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) ?? ""
Upvotes: 7
Reputation: 54795
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
Upvotes: 2