美文网首页
长数字,3位逗号隔开

长数字,3位逗号隔开

作者: 逍遥庄主 | 来源:发表于2019-03-14 17:59 被阅读0次

    自由发挥,自由延伸,自由处理

    +(NSString*)resetCountNumAndChangeformat:(NSString*)number{
        number = [self xy_ConvertNumString:number];
        NSString*divide =@",";
        NSString*integer =@"";
        NSString*radixPoint =@"";
        BOOL contains =NO;
        if([number containsString:@"."]) {
            contains =YES;
            // 若传入浮点数,则需要将小数点后的数字分离出来
            NSArray *comArray = [number componentsSeparatedByString:@"."];
            integer = [comArray firstObject];
            radixPoint = [comArray lastObject];
        }else{
            integer = number;
        }
        // 将整数按各个字符为一组拆分成数组
        if(integer.length<=6) {
            return[self xy_ConvertNumString:number];
        }
        NSMutableArray *integerArray = [[NSMutableArray alloc] init];
        for(int i =0; i < integer.length; i ++) {
            NSString*subString = [integer substringWithRange:NSMakeRange(i,1)];
            [integerArray addObject: subString];
        }
        // 将整数数组倒序每隔3个字符添加一个逗号“,”
        NSString*newNumber =@"";
        for(NSInteger i =0; i < integerArray.count; i ++) {
            NSString*getString =@"";
            NSInteger index = (integerArray.count-1) - i;
            if(integerArray.count> index) {
                getString = [integerArray objectAtIndex:index];
            }
            BOOL result =YES;
            if(index ==0&& integerArray.count%3==0) {
                result =NO;
            }
            if((i+1)%3==0&& result) {
                newNumber = [NSString stringWithFormat:@"%@%@%@",divide,getString,newNumber];
            }else{
                newNumber = [NSString stringWithFormat:@"%@%@",getString,newNumber];
            }
        }
        if(contains) {
            newNumber = [NSString stringWithFormat:@"%@.%@",newNumber,radixPoint];
        }
        return  newNumber;
    }
    +(NSString *)xy_ConvertNumString:(NSString *)string {
        return [NSString stringWithFormat:@"%.2f",floor([string doubleValue]*100)/100];
    }
    

    相关文章

      网友评论

          本文标题:长数字,3位逗号隔开

          本文链接:https://www.haomeiwen.com/subject/ubmcmqtx.html