金额字段加千位分隔符方法
2016-08-09 本文已影响116人
HeavenWong
- (NSString *)separatedDigitStringWithStr:(NSString *)digitString
{
/*
// 如果带两位小数
NSString *endStr = [digitString substringFromIndex:digitString.length - 3];
if (digitString.length - 3 <= 3) {
return digitString;
} else {
NSMutableString *processString = [NSMutableString stringWithString:digitString];
NSInteger location = processString.length - 3 - 3;
*/
if (digitString.length <= 3) {
return digitString;
} else {
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];
int 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;
}
}
效果图