demo: 源码下载:DMLimtDemo.rar
之前做电商类APP时,针对稍大的金额展示时,需要每隔千位添加逗号便于用户识别。
逻辑比较简单,这里按需要写了一个可选前后缀的一个转换方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
# 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;
}
}
- (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位用逗号分隔,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:http://blog.csdn.net/wsyx768/article/details/77833214