iOS 數字每隔3位用逗號分隔

需求:spa

1.只有整數,沒有小數code

+(NSString *)stringWithCharmCount:(NSString *)charmCount
{
    //將要分割的字符串變爲可變字符串
    NSMutableString *countMutStr = [[NSMutableString alloc]initWithString:charmCount];
    //字符串長度
    NSInteger length = countMutStr.length;
    //除數
    NSInteger divisor = length/3;
    //餘數
    NSInteger remainder = length%3;
    //有多少個逗號
    NSInteger commaCount;
    if (remainder == 0) {   //當餘數爲0的時候,除數-1==逗號數量
        commaCount = divisor - 1;
    }else{  //不然 除數==逗號數量
        commaCount = divisor;
    }
    //根據逗號數量,for循環依次添加逗號進行分隔
    for (int i = 1; i<commaCount+1; i++) {
        [countMutStr insertString:@"," atIndex:length - i * 3];
    }
    return countMutStr;
}
相關文章
相關標籤/搜索