Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: How to format string as $ Price

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

like image 980
Mustafa Avatar asked Nov 21 '09 09:11

Mustafa


3 Answers

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.

like image 129
Rhult Avatar answered Oct 16 '22 10:10

Rhult


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.

like image 37
outis Avatar answered Oct 16 '22 10:10

outis


You need to get rid of the ' character

So, just have this:

NSString *priceString = [NSString localizedStringWithFormat:@"$ %.2f", price];
like image 36
user2053111 Avatar answered Oct 16 '22 10:10

user2053111