将数字转为每隔3位整数由逗号“,”分隔的字符串

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

你可能感兴趣的:(将数字转为每隔3位整数由逗号“,”分隔的字符串)