有没有一种简单的方法可以在 iOS 中将货币格式化为字符串? [英] Is there a simple way to format currency into string in iOS?

查看:21
本文介绍了有没有一种简单的方法可以在 iOS 中将货币格式化为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的游戏使用自定义字体,并且它们无法包含所有可用 App Store 货币(如英镑)的符号.所以我认为最好回滚到货币的字符串表示.

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.

所使用的方法对于 App Store 支持的任何货币应该是绝对可以的.

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

推荐答案

如果您希望将其本地化(即价格正确一侧的货币),那就有点麻烦了.

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];

必须使用从 SKProduct 获得的语言环境.不要使用 [NSLocale currentLocale]!

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

这篇关于有没有一种简单的方法可以在 iOS 中将货币格式化为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆