在日常开发中,常常需要对金额加逗号来显示,我把这件事放在NSString的分类里来做,直接加一个类方法。
+(NSString*)strmethodComma:(NSString*)string
{
if (!string || [string isEqualToString:@"0"]) {
return @"0.00";
}
NSString *sign = nil;
if ([string hasPrefix:@"-"]||[string hasPrefix:@"+"]) {
sign = [string substringToIndex:1];
string = [string substringFromIndex:1];
}
if (string.length < 4) {
if (sign) {
string = [sign stringByAppendingString:string];
}
return string;
}
NSString *pointLast = nil;
NSString *pointFront = nil;
NSInteger location = [string rangeOfString:@"."].location;
if (location != NSNotFound) {
NSString *substring = [string substringFromIndex:location];
pointLast = [string substringFromIndex:[string length]-substring.length];
pointFront = [string substringToIndex:[string length]-substring.length];
}else {
pointLast = @"";
pointFront = string;
}
int commaNum = ([pointFront length]-1)/3;
NSMutableArray *arr = [NSMutableArray array];
for (int i = 0; i < commaNum+1; i++) {
int index = [pointFront length] - (i+1)*3;
int leng = 3;
if(index < 0)
{
leng = 3+index;
index = 0;
}
NSRange range = {index,leng};
NSString *stq = [pointFront substringWithRange:range];
[arr addObject:stq];
}
NSMutableArray *arr2 = [NSMutableArray array];
for (int i = [arr count]-1; i>=0; i--) {
[arr2 addObject:arr[i]];
}
NSString *commaString = [[arr2 componentsJoinedByString:@","] stringByAppendingString:pointLast];
// NSArray *ary = [commaString componentsSeparatedByString:@","];
if (sign) {
commaString = [sign stringByAppendingString:commaString];
}
return commaString;
}