iOS 数字每隔3位用逗号分隔

需求:

1.只有整数,没有小数

方法一:也是最笨的方法,通过for循环来添加

+(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;
}

 方法二:使用系统的方法

let formatter: NumberFormatter = NumberFormatter()
formatter.positiveFormat = "###,###"
let money = 21321312.122
self.numberLabel.text = formatter.string(from: NSNumber(value: money))

如果保留两位小数,则字符串为"###,###.00"

原文地址:https://www.cnblogs.com/ChengYing-Freedom/p/8516012.html