Objective-C:如何将字符串格式化为$ Price

时间:2021-04-10 19:20:57

Is their a built-in way of formatting string as $ price, e.g. 12345.45 converted to $12,345.45?

它们是将字符串格式化为$ price(例如12345.45转换为$ 12345.45)的内置方式吗?

4 个解决方案

#1


66  

Assuming you are using Cocoa (or just Foundation), you can use NSNumberFormatter and set its style to currency:

假设您使用的是Cocoa(或仅仅是Foundation),您可以使用NSNumberFormatter并将其样式设置为货币:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
... = [formatter stringFromNumber:number];

By default it uses the locale of your system, but you can change that and lots of other properties, see the NSNumberFormatter API docs.

默认情况下,它使用您的系统的语言环境,但是您可以更改它和许多其他属性,请参阅NSNumberFormatter API文档。

#2


4  

Assuming the price is held in a float, you probably want +localizedStringWithFormat:.

假设价格是浮动的,你可能想要+localizedStringWithFormat:。

NSString *priceString = [NSString localizedStringWithFormat:@"$ %'.2f",price];

Hmmm... Apple says they follow the IEEE standard for printf, so it should accept the ' flag, but it doesn't work on Tiger. NSNumberFormatter it is.

嗯…苹果表示,他们遵循了printf的IEEE标准,因此它应该接受“flag,但它不支持Tiger”。NSNumberFormatter。

#3


1  

You need to get rid of the ' character

你需要摆脱“角色”

So, just have this:

所以,只有这个:

NSString *priceString = [NSString localizedStringWithFormat:@"$ %.2f", price];

#4


0  

NSString *formatedNumbers = [NSNumberFormatter localizedStringFromNumber:myNumber numberStyle:NSNumberFormatterCurrencyStyle];

#1


66  

Assuming you are using Cocoa (or just Foundation), you can use NSNumberFormatter and set its style to currency:

假设您使用的是Cocoa(或仅仅是Foundation),您可以使用NSNumberFormatter并将其样式设置为货币:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
... = [formatter stringFromNumber:number];

By default it uses the locale of your system, but you can change that and lots of other properties, see the NSNumberFormatter API docs.

默认情况下,它使用您的系统的语言环境,但是您可以更改它和许多其他属性,请参阅NSNumberFormatter API文档。

#2


4  

Assuming the price is held in a float, you probably want +localizedStringWithFormat:.

假设价格是浮动的,你可能想要+localizedStringWithFormat:。

NSString *priceString = [NSString localizedStringWithFormat:@"$ %'.2f",price];

Hmmm... Apple says they follow the IEEE standard for printf, so it should accept the ' flag, but it doesn't work on Tiger. NSNumberFormatter it is.

嗯…苹果表示,他们遵循了printf的IEEE标准,因此它应该接受“flag,但它不支持Tiger”。NSNumberFormatter。

#3


1  

You need to get rid of the ' character

你需要摆脱“角色”

So, just have this:

所以,只有这个:

NSString *priceString = [NSString localizedStringWithFormat:@"$ %.2f", price];

#4


0  

NSString *formatedNumbers = [NSNumberFormatter localizedStringFromNumber:myNumber numberStyle:NSNumberFormatterCurrencyStyle];