Is there a simple way to format currency into string in iOS? Is there a simple way to format currency into string in iOS? objective-c objective-c

Is there a simple way to format currency into string in iOS?


If you want it localized (ie the currency on the correct side of the price) it is a bit of a hassle.

NSDecimalNumber *price = [NSDecimalNumber decimalNumberWithString:@"1.99"];NSLocale *priceLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"de_DE"] autorelease]; // get the locale from your SKProductNSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];[currencyFormatter setLocale:priceLocale];NSString *currencyString = [currencyFormatter internationalCurrencySymbol]; // EUR, GBP, USD...NSString *format = [currencyFormatter positiveFormat];format = [format stringByReplacingOccurrencesOfString:@"¤" withString:currencyString];    // ¤ is a placeholder for the currency symbol[currencyFormatter setPositiveFormat:format];NSString *formattedCurrency = [currencyFormatter stringFromNumber:price];

You have to use the locale you get from the SKProduct. Don't use [NSLocale currentLocale]!


The – productsRequest:didReceiveResponse: method gives you back a list of SKProducts.

Each product contains a property priceLocale which contains the local currency of the product for the current user.

You could use the following sample code (apple's) to format it:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];[numberFormatter setLocale:product.priceLocale];NSString *formattedString = [numberFormatter stringFromNumber:product.price];

Good luck!


The Swift Example:

var currencyFormatter = NSNumberFormatter()currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStylecurrencyFormatter.locale = priceLocale //SKProduct->priceLocalevar currencyString = currencyFormatter.internationalCurrencySymbolvar format = currencyFormatter.positiveFormatformat = format.stringByReplacingOccurrencesOfString("¤", withString: currencyString)currencyFormatter.positiveFormat = formatvar formattedCurrency = currencyFormatter.stringFromNumber(price) //SKProduct->priceprintln("formattedCurrency: \(formattedCurrency)")//formattedCurrency: 0,89 EUR