Objective-C: How to format string as $ Price

£可爱£侵袭症+ 提交于 2019-11-27 21:53:50

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

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.

Assuming the price is held in a float, you probably want +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.

user2053111

You need to get rid of the ' character

So, just have this:

NSString *priceString = [NSString localizedStringWithFormat:@"$ %.2f", price];
NSString *formatedNumbers = [NSNumberFormatter localizedStringFromNumber:myNumber numberStyle:NSNumberFormatterCurrencyStyle];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!