NSNumberFormatter 金额格式化
NSNumber *number = [NSNumber numberWithDouble:123456789.987654]; // 四舍五入的整数 123456790 NSNumberFormatter *format0 = [NSNumberFormatter localizedStringFromNumber:number numberStyle:NSNumberFormatterNoStyle]; // 小数形式 123,456,789.988 NSNumberFormatter *format1 = [NSNumberFormatter localizedStringFromNumber:number numberStyle:NSNumberFormatterDecimalStyle]; // 货币形式(本地化) $123,456,789.99 NSNumberFormatter *format2 = [NSNumberFormatter localizedStringFromNumber:number numberStyle:NSNumberFormatterCurrencyStyle]; // 百分数形式 12,345,678,999% NSNumberFormatter *format3 = [NSNumberFormatter localizedStringFromNumber:number numberStyle:NSNumberFormatterPercentStyle]; // 科学计数法 1.23456789987654E8 NSNumberFormatter *format4 = [NSNumberFormatter localizedStringFromNumber:number numberStyle:NSNumberFormatterScientificStyle]; // 朗读形式 (one hundred twenty-three million four hundred fifty-six thousand seven hundred eighty-nine point nine eight seven six five four) NSNumberFormatter *format5 = [NSNumberFormatter localizedStringFromNumber:number numberStyle:NSNumberFormatterSpellOutStyle]; // 序数形式 123,456,790th NSNumberFormatter *format6 = [NSNumberFormatter localizedStringFromNumber:number numberStyle:NSNumberFormatterOrdinalStyle]; // 货币形式 ISO (本地化) USD123,456,789.99 NSNumberFormatter *format7 = [NSNumberFormatter localizedStringFromNumber:number numberStyle:NSNumberFormatterCurrencyISOCodeStyle]; // 货币形式(本地化) 123,456,789.99 US dollars NSNumberFormatter *format8 = [NSNumberFormatter localizedStringFromNumber:number numberStyle:NSNumberFormatterCurrencyPluralStyle]; // 会计计数(本地化) $123,456,789.99 NSNumberFormatter *format9 = [NSNumberFormatter localizedStringFromNumber:number numberStyle:NSNumberFormatterCurrencyAccountingStyle];
用两种方法实现金额格式化
- (NSString *)formatString:(NSString *)string { NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; [formatter setPositiveFormat:@"###,##0.00"]; return [formatter stringFromNumber:@([string doubleValue])]; }
@interface NSString (RMB) - (NSString *)RMBFormatString; @end #import "NSString+RMB.h" @implementation NSString (RMB) - (NSString *)RMBFormatString { NSString *number = self; if ([number doubleValue] > 0) { number = [NSString stringWithFormat:@"%.2f",[number doubleValue]]; NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc]init]; numFormatter.numberStyle = NSNumberFormatterDecimalStyle; NSNumber *num = [NSNumber numberWithDouble:[number doubleValue]]; NSString *str = [NSString stringWithFormat:@"%@",[numFormatter stringFromNumber:num]]; if ([str rangeOfString:@"."].length > 0) { NSString *floatStr = [str componentsSeparatedByString:@"."][1]; if (floatStr.length == 1) { str = [NSString stringWithFormat:@"%@0",str]; } else{ str = [str substringToIndex:([str rangeOfString:@"."].location + 3)]; } return [NSString stringWithFormat:@"¥%@",str]; } else{ return [NSString stringWithFormat:@"¥%@.00",str]; } } else { return @"¥0.00"; } } @end