当前位置: 移动技术网 > IT编程>移动开发>IOS > [iOS]数字每隔3位用逗号分隔

[iOS]数字每隔3位用逗号分隔

2018年10月13日  | 移动技术网IT编程  | 我要评论

天使公主伴奏,常音儿,空心菜

[ios]数字每隔3位用逗号分隔

之前做电商类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 *pide = @",";

    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:@"%@%@%@",pide,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

示意图:

\

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网