views:

109

answers:

3

I'm using an NSDecimalNumber to store money in Core Data. I naively used stringWithFormat: at first to format the value, later realizing that it didn't support NSDecimalNumber and was instead formatting the pointer :(. So after some reading through the docs I learned to use the NSNumberFormatter to get the format I wanted. But this just strikes me as the "hard way". Is there any easier way than this:?

NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle: NSNumberFormatterCurrencyStyle];
priceField.text = [formatter stringFromNumber: ent.price];
[formatter release];
+4  A: 

There's nothing wrong with that approach, and it's the conventional pattern to convert opaque number classes to strings.

If I have a UIView that uses a formatter often, I'll usually have one as an instance member so I avoid having to repeatedly alloc/init/release the formatter.

Shaggy Frog
A: 

NSNumberFormatter can be expensive, why not just call [ent descriptionWithLocale:]

jarjar
From what I can tell in the docs, that doesn't provide a way to format currency.
Paul Alexander
+1  A: 

Just convert it to a double and use "F"

[NSString stringWithFormat:@"%1.2F", [ent doubleValue]];

Steven Bristol