开发者

Is NSNumberFormatter the only way to format an NSDecimalNumber?

开发者 https://www.devze.com 2023-01-01 20:15 出处:网络
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 s开发者_Go百科upport NSDecimalNumber and was i

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 s开发者_Go百科upport 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];


on iOS 4.0 and later you can use this method:

NSString* currencyString = [NSNumberFormatter 
                                 localizedStringFromNumber:number
                                 numberStyle:NSNumberFormatterCurrencyStyle];


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.


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


Just convert it to a double and use "F"

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

0

精彩评论

暂无评论...
验证码 换一张
取 消