iOS 数字金额每隔三位逗号隔开

+ (NSString*)strmethodComma:(NSString*)string withFormatting:(NSInteger)formatting

{
    
    NSString *sign = nil;
    NSString *point = nil;
    NSString *commaString = nil;
    NSInteger leng = formatting;
    
    if ([string hasPrefix:@"-"]||[string hasPrefix:@"+"]) {
        
        sign = [string substringToIndex:1];
        
        string = [string substringFromIndex:1];
        
    }
    
    if ([string containsString:@"."]){
        NSArray *tempArr = [string componentsSeparatedByString:@"."];
        point = tempArr.lastObject;
        string = tempArr.firstObject;
    }
    
    
    if (string.length <= leng) {
        commaString = string;
    }else{
        NSMutableArray *arr = [NSMutableArray array];
        
        for (NSInteger i = string.length; i > 0; i = i - leng) {
            NSString *stq = @"";
            if (i - leng >= 0) {
                NSRange range = NSMakeRange(i - leng, leng);
                stq = [string substringWithRange:range];
            }else{
                NSRange range = NSMakeRange(0, i);
                stq = [string substringWithRange:range];
            }
            [arr addObject:stq];
        }
        for (NSString *str in arr) {
            if (commaString) {
                commaString = [NSString stringWithFormat:@"%@,%@",str,commaString];
            }else{
                commaString = str;
            }
            
        }
    }
    
    
    if (sign) {
        
        commaString = [sign stringByAppendingString:commaString];
        
    }
    if (point) {
        
        commaString = [commaString stringByAppendingString:[NSString stringWithFormat:@".%@",point]];
        
    }
    
    return commaString;
    
}

你可能感兴趣的:(iOS 数字金额每隔三位逗号隔开)