Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need a way to format the price from NSNumber into a string like this: "USD 0.99", not "$ 0.99".

My game uses custom fonts, and they could not have the symbols for all the available App Store currencies like GBP. So I think it's better to roll-back to string representation of currency.

The method used should be absolutely OK for any currency that App Store supports.

like image 878
Hedin Avatar asked Feb 24 '11 13:02

Hedin


People also ask

How do you format Currency value?

On the Home tab, click the Dialog Box Launcher next to Number. Tip: You can also press Ctrl+1 to open the Format Cells dialog box. In the Format Cells dialog box, in the Category list, click Currency or Accounting. In the Symbol box, click the currency symbol that you want.

How do I change the Currency on Apple numbers?

Currency (units of monetary value) Select the cells or table you want to format. In the Format sidebar, click the Cell tab, then click the Data Format pop-up menu and choose Currency.


2 Answers

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 SKProduct

NSNumberFormatter *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]!

like image 115
Matthias Bauch Avatar answered Sep 19 '22 12:09

Matthias Bauch


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!

like image 39
Tieme Avatar answered Sep 21 '22 12:09

Tieme