OC 千位分隔符格式化数字
工作中总是碰到很多需求,比如金额需要以千位分隔的方式显示,这是OC版本转换方法,其它语言的可参考,代码如下:
/**
转换目标字符串为千位分隔显示
@param digitString 目标字符串
@return 转换结果字符串
*/
+ (NSString *)groupedThousandsDigitStringWithStr:(NSString *)digitString {
// 判断小数部位
NSRange rangeOfPoint = [digitString rangeOfString:@"."];
NSString *pointStr = @"";
if (rangeOfPoint.length >= 1) {
pointStr = [digitString substringFromIndex:rangeOfPoint.location];
}
// 去掉小数部位
digitString = [digitString substringToIndex:rangeOfPoint.location];
// 去掉小数位后长度小于3直接返回原字符
if (digitString.length <= 3) return [digitString stringByAppendingString:pointStr];
NSMutableString *processString = [NSMutableString stringWithString:digitString];
NSInteger location = processString.length - 3;
NSMutableArray *processArray = [NSMutableArray array];
while (location >= 0) {
NSString *temp = [processString substringWithRange:NSMakeRange(location, 3)];
[processArray addObject:temp];
if (location < 3 && location > 0) {
NSString *t = [processString substringWithRange:NSMakeRange(0, location)];
[processArray addObject:t];
}
location -= 3;
}
NSMutableArray *resultsArray = [NSMutableArray array];
NSInteger k = 0;
for (NSString *str in processArray) {
k++;
NSMutableString *tmp = [NSMutableString stringWithString:str];
if (str.length > 2 && k < processArray.count ) {
[tmp insertString:@"," atIndex:0];
[resultsArray addObject:tmp];
} else {
[resultsArray addObject:tmp];
}
}
NSMutableString *resultString = [NSMutableString string];
for (NSInteger i = resultsArray.count - 1 ; i >= 0; i--) {
NSString *tmp = [resultsArray objectAtIndex:i];
[resultString appendString:tmp];
}
return [resultString stringByAppendingString:pointStr];
}