Create a gist now

Instantly share code, notes, and snippets.

NSString category for formatting numbers easily with optional NSNumberFormatter settings as block
// use it. get rid of `autorelease` if using arc.
//
// .h file
@interface NSString (FMNumberFormatter)
+ (NSString *)stringByFormattingNumber:(NSNumber*)number
formatterSettings:(void(^)(NSNumberFormatter* formatter))settingsBlock;
@end
// .m file
@implementation NSString (FMNumberFormatter)
+ (NSString *)stringByFormattingNumber:(NSNumber*)number
formatterSettings:(void(^)(NSNumberFormatter* formatter))settingsBlock {
__block NSNumberFormatter *nf = [NSNumberFormatter.new autorelease];
if (settingsBlock) {
settingsBlock(nf);
}
return [nf stringFromNumber:number];
}
@end
// usage
NSString* formattedNumber = [NSString stringByFormattingNumber:@(3500)
formatterSettings:^(NSNumberFormatter *formatter) {
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
formatter.currencyCode = @"JPY";
formatter.groupingSize = 3;
formatter.groupingSeparator = @",";
formatter.usesGroupingSeparator = YES;
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment