- (NSString *)moneyFormat:(NSString *)money {
if (!money || money.length == 0) {
return money;
}
BOOL hasPoint = NO;
if ([money rangeOfString:@"."].length > 0) {
hasPoint = YES;
}
NSMutableString *pointMoney = [NSMutableString stringWithString:money];
if (hasPoint == NO) {
[pointMoney appendString:@".00"];
}
NSArray *moneys = [pointMoney componentsSeparatedByString:@"."];
if (moneys.count > 2) {
return pointMoney;
} else if (moneys.count == 1) {
return [NSString stringWithFormat:@"%@.00", moneys[0]];
} else {
// 整数部分每隔 3 位插入一个逗号
NSString *frontMoney = [self stringFormatToThreeBit:moneys[0]];
if ([frontMoney isEqualToString:@""]) {
frontMoney = @"0";
}
// 拼接整数和小数两部分
NSString *backMoney = moneys[1];
if ([backMoney length] == 1) {
return [NSString stringWithFormat:@"%@.%@0", frontMoney, backMoney];
} else if ([backMoney length] > 2) {
return [NSString stringWithFormat:@"%@.%@", frontMoney, [backMoney substringToIndex:2]];
} else {
return [NSString stringWithFormat:@"%@.%@", frontMoney, backMoney];
}
}
}
- (NSString *)stringFormatToThreeBit:(NSString *)string {
NSString *tempString = [string stringByReplacingOccurrencesOfString:@"," withString:@""];
NSMutableString *mutableString = [NSMutableString stringWithString:tempString];
NSInteger n = 2;
for (NSInteger i = tempString.length - 3; i > 0; i--) {
n++;
if (n == 3) {
[mutableString insertString:@"," atIndex:i];
n = 0;
}
}
return mutableString;
}
- (NSString *)formatDecimalNumber:(NSString *)string {
if (!string || string.length == 0) {
return string;
}
NSNumber *number = @([string doubleValue]);
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = kCFNumberFormatterDecimalStyle;
formatter.positiveFormat = @"###,##0.00";
NSString *amountString = [formatter stringFromNumber:number];
return amountString;
}