有没有一种简单的方法可以在iOS中将货币格式化为字符串?

Hed*_*din 14 iphone currency objective-c app-store ios

我需要一种方法将NSNumber的价格格式化为这样的字符串:"USD 0.99",而不是"0.99美元".

我的游戏使用自定义字体,并且它们没有所有可用App Store货币(如GBP)的符号.所以我认为回滚到货币的字符串表示更好.

对于App Store支持的任何货币,使用的方法应该绝对正常.

Mat*_*uch 36

如果你想要它本地化(即价格正确的货币),这有点麻烦.

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];
Run Code Online (Sandbox Code Playgroud)

必须使用从SKProduct获得的区域设置.不要使用[NSLocale currentLocale]!

  • '¤'是[通用货币符号](http://www.theasciicode.com.ar/extended-ascii-code/generic-currency-sign-ascii-code-207.html).当设计ascii时,没有足够的空间来包含所有货币符号,因此只有少数货币符号包括:Dollar $,Yen¥,Pounds£.工程师觉得他们应该包含代表"货币"的符号.他们决定使用金币(你能看到它闪耀吗?) (2认同)

Tie*_*eme 8

– productsRequest:didReceiveResponse:方法为您提供了SKProducts列表.

每个产品都包含一个属性priceLocale,该属性包含当前用户的产品的本地货币.

您可以使用以下示例代码(apple's)进行格式化:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setLocale:product.priceLocale];
NSString *formattedString = [numberFormatter stringFromNumber:product.price];
Run Code Online (Sandbox Code Playgroud)

祝好运!


Joh*_*ker 1

实现此目的的最简单方法是使用NSNumberFormatter类根据需要格式化 NSNumber 值。

虽然方法太多,无法一一提及,但这提供了多种输出格式化功能,包括setInternationalCurrencySymbol:应该特别感兴趣的方法。