欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-11-05 12:08:56
[ios]数字每隔3位用逗号分隔 之前做电商类app时,针对稍大的金额展示时,需要每隔千位添加逗号便于用户识别。 逻辑比较简单,这里按需要写了一个可选前后缀的一个转换方法: #import &q...

[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

示意图:

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