Is their a built-in way of formatting string as $ price, e.g. 12345.45 converted to $12,345.45?
Asked
Active
Viewed 2.3k times
29
Michał Powaga
- 22,561
- 8
- 51
- 62
Mustafa
- 20,504
- 42
- 146
- 209
-
What type is holding the number? – outis Nov 21 '09 at 09:08
4 Answers
70
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.
Rhult
- 1,646
- 15
- 10
5
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.
outis
- 75,655
- 22
- 151
- 221
3
You need to get rid of the ' character
So, just have this:
NSString *priceString = [NSString localizedStringWithFormat:@"$ %.2f", price];
n00begon
- 3,503
- 3
- 29
- 42
user2053111
- 39
- 1
0
NSString *formatedNumbers = [NSNumberFormatter localizedStringFromNumber:myNumber numberStyle:NSNumberFormatterCurrencyStyle];
Ulle Tad
- 345
- 1
- 4
- 15