demo: 源码下载:http://xiazai.zyiz.net/201709/yuanma/DMLimtDemo_jb51.rar
之前做电商类APP时,针对稍大的金额展示时,需要每隔千位添加逗号便于用户识别。
逻辑比较简单,这里按需要写了一个可选前后缀的一个转换方法:
#import "DMViewController.h" @interface DMViewController () @property (weak, nonatomic) IBOutlet UITextField *titleText; @property (weak, nonatomic) IBOutlet UILabel *numLab; @end @implementation DMViewController - (IBAction)tapButtonAction:(id)sender { UIButton *tempBut = (UIButton *)sender; if (tempBut.isSelected) { tempBut.selected = NO; _numLab.text = @"label"; } else { tempBut.selected = YES; NSString *newNumber = [self separateNumberUseCommaWith:_titleText.text]; _numLab.text = newNumber; } } // 将数字转为每隔3位整数由逗号“,”分隔的字符串 - (NSString *)separateNumberUseCommaWith:(NSString *)number { // 前缀 NSString *prefix = @"¥"; // 后缀 NSString *suffix = @"元"; // 分隔符 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; } // 将整数按各个字符为一组拆分成数组 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]; } if (![prefix isEqualToString:@""]) { newNumber = [NSString stringWithFormat:@"%@%@",prefix,newNumber]; } if (![suffix isEqualToString:@""]) { newNumber = [NSString stringWithFormat:@"%@%@",newNumber,suffix]; } return newNumber; } @end
示意图:
总结
以上所述是小编给大家介绍的iOS开发之数字每隔3位用逗号分隔,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对找一找教程网网站的支持!