iOS 千分符

本文介绍了一种使用Objective-C实现的数字格式化方法,能够将长数字以千分位符号进行分隔显示,提供了两种实现方式:一种适用于字符串类型的数字输入,另一种则直接处理整数类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

01#import "Math.h"
02 
03@implementation Math
04 
05+(BOOL)isNumber:(char)c
06{
07    for(inti=0;i<9;i++)
08    {
09        if(i==c-'0') {
10            returnYES;
11        }
12    }
13    returnNO;
14}
15 
16+(NSString *)getQianFenFu:(NSString *)price
17{
18    if(!price)
19    {
20        returnNULL;
21    }
22     
23    if([self isNumber:[price characterAtIndex:0]])
24    {
25        NSMutableString *sb;
26        NSString *oldPrice=price;
27        [oldPrice retain];
28        intx=[oldPrice length]%3;
29        intxx=[oldPrice length]/3;
30        sb=[[NSMutableString alloc]init];
31         
32        NSString *s1=[[oldPrice substringToIndex:x]stringByAppendingFormat:@","];
33        [sb appendString:s1];
34         
35        for(inti=0;i<xx;i++)
36        {
37            [sb appendString:[[oldPrice substringWithRange:NSMakeRange((x+(3*i)),3)]stringByAppendingFormat:@","]];
38        }
39        NSString *str=[NSString stringWithFormat:sb];
40        [sb release];
41        [oldPrice release];
42         
43        for(int i=0; i<[str length]; i++)
44        {
45            charc1=[str characterAtIndex:0];
46            charc2=[str characterAtIndex:[str length]-1];
47             
48            if([self isNumber:c1] && [self isNumber:c2])
49            {}
50            elseif([self isNumber:c1])
51            {
52                str =[str substringWithRange:NSMakeRange(0, [str length]-1)];
53            }
54            elseif([self isNumber:c2])
55            {
56                str =[str substringWithRange:NSMakeRange(1, [str length])];
57            }
58            else
59            {
60                str =[str substringWithRange:NSMakeRange(1, [str length]-1)];
61            }
62        }
63        returnstr;
64    }
65     
66    returnNULL;
67}
68 
69@end








更简单的


+ (NSString *)getQianFenFu:(long long)number {
        if (number < 1000) {
                return [NSString stringWithFormat:@"%d", number];
        }
       
        return [[self getQianFenFu:number/1000] stringByAppendingFormat:@",%03d", number%1000];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值