您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)iOS中如何實現(xiàn)數(shù)字每隔3位用逗號分隔,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
之前做電商類APP時,針對稍大的金額展示時,需要每隔千位添加逗號便于用戶識別。
邏輯比較簡單,這里按需要寫了一個可選前后綴的一個轉(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ù)由逗號“,”分隔的字符串 - (NSString *)separateNumberUseCommaWith:(NSString *)number { // 前綴 NSString *prefix = @"¥"; // 后綴 NSString *suffix = @"元"; // 分隔符 NSString *divide = @","; NSString *integer = @""; NSString *radixPoint = @""; BOOL contains = NO; if ([number containsString:@"."]) { contains = YES; // 若傳入浮點數(shù),則需要將小數(shù)點后的數(shù)字分離出來 NSArray *comArray = [number componentsSeparatedByString:@"."]; integer = [comArray firstObject]; radixPoint = [comArray lastObject]; } else { integer = number; } // 將整數(shù)按各個字符為一組拆分成數(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個字符添加一個逗號“,” 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中如何實現(xiàn)數(shù)字每隔3位用逗號分隔”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。