這篇文章將為大家詳細(xì)講解有關(guān)iOS中如何實(shí)現(xiàn)數(shù)字每隔3位用逗號(hào)分隔,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
創(chuàng)新互聯(lián)專注于振興企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站設(shè)計(jì),商城網(wǎng)站定制開發(fā)。振興網(wǎng)站建設(shè)公司,為振興等地區(qū)提供建站服務(wù)。全流程按需求定制開發(fā),專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)
之前做電商類APP時(shí),針對(duì)稍大的金額展示時(shí),需要每隔千位添加逗號(hào)便于用戶識(shí)別。
邏輯比較簡(jiǎn)單,這里按需要寫了一個(gè)可選前后綴的一個(gè)轉(zhuǎn)換方法:
#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; } } // 將數(shù)字轉(zhuǎn)為每隔3位整數(shù)由逗號(hào)“,”分隔的字符串 - (NSString *)separateNumberUseCommaWith:(NSString *)number { // 前綴 NSString *prefix = @"¥"; // 后綴 NSString *suffix = @"元"; // 分隔符 NSString *divide = @","; NSString *integer = @""; NSString *radixPoint = @""; BOOL contains = NO; if ([number containsString:@"."]) { contains = YES; // 若傳入浮點(diǎn)數(shù),則需要將小數(shù)點(diǎn)后的數(shù)字分離出來 NSArray *comArray = [number componentsSeparatedByString:@"."]; integer = [comArray firstObject]; radixPoint = [comArray lastObject]; } else { integer = number; } // 將整數(shù)按各個(gè)字符為一組拆分成數(shù)組 NSMutableArray *integerArray = [[NSMutableArray alloc] init]; for (int i = 0; i < integer.length; i ++) { NSString *subString = [integer substringWithRange:NSMakeRange(i, 1)]; [integerArray addObject:subString]; } // 將整數(shù)數(shù)組倒序每隔3個(gè)字符添加一個(gè)逗號(hào)“,” 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
示意圖:
關(guān)于“iOS中如何實(shí)現(xiàn)數(shù)字每隔3位用逗號(hào)分隔”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。