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)
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) ?? ""
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With