iOS开发之数字每隔3位用逗号分隔
程序员文章站
2023-12-20 20:19:46
demo: 源码下载:http://xiazai.jb51.net/201709/yuanma/dmlimtdemo_jb51.rar
之前做电商类app时,针对稍大的金...
demo: 源码下载:http://xiazai.jb51.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位用逗号分隔,希望对大家有所帮助