How to add commas to number every 3 digits in Objective C?

后端 未结 9 738

If I have a number int aNum = 2000000 how do I format this so that I can display it as the NSString 2,000,000?

9条回答
  •  鱼传尺愫
    2020-11-28 03:26

    For those who need to do it with strings of numbers and not just integers (I.e. Big Numbers) I made the following macro:

    #define addCommas(__string) (\
    (^NSString *(void){\
    NSString *__numberString = __string;\
    NSString *__integerPortion = __numberString;\
    NSString *__decimalPortion = @"";\
    if ([__string containsString:@"."]) {\
    __integerPortion = [__numberString componentsSeparatedByString:@"."][0];\
    __decimalPortion = st(@".%@", [__numberString componentsSeparatedByString:@"."][1]);\
    }\
    int __i = (int)__integerPortion.length-3;\
    while (__i > 0) {\
    __integerPortion = st(@"%@,%@", substringInRange(__integerPortion, 0, __i), substringInRange(__integerPortion, __i, (int)__integerPortion.length));\
    __i -= 3;\
    }\
    __numberString = st(@"%@%@", __integerPortion, __decimalPortion);\
    return __numberString;\
    })()\
    )
    

提交回复
热议问题