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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1774982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 22:31:44  来源:igfitidea点击:

Objective-C: How to format string as $ Price

objective-cformattingcurrency

提问by Mustafa

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

它们是将字符串格式化为 $ price 的内置方式,例如12345.45转换为$12,345.45

回答by Rhult

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 NSNumberFormatterAPI docs.

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

回答by outis

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. NSNumberFormatterit is.

嗯... Apple 表示他们遵循IEEE 标准 printf,因此它应该接受 ' 标志,但它不适用于 Tiger。NSNumberFormatter这是。

回答by user2053111

You need to get rid of the 'character

你需要摆脱这个'角色

So, just have this:

所以,只要这个:

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

回答by Ula

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