格式化字符串

目录:
1、补齐两位小数
2、金额字符串处理
3、设置卡号的显示格式

1、补齐传入字符串(string)小数点后两位,返回两位小数字符串

+(NSString *)setTwoPointStr:(NSString *)string
{
    NSMutableString *tempStr = [[NSMutableString alloc] initWithString:string];

     //判断是否包含小数点
    if([tempStr rangeOfString:@"."].location != NSNotFound)
    {
        if([tempStr substringFromIndex:[tempStr rangeOfString:@"."].location].length > 3)
        {
            //如果小数部分超过两位,只取两位
            tempStr = [[NSMutableString alloc] initWithFormat:@"%.2f",[tempStr doubleValue]];
        }
        else if([tempStr substringFromIndex:[tempStr rangeOfString:@"."].location].length<3)
        {
            //如果小数部分不足两位,则补充0
            [tempStr appendString:@"0"];
        }
    }
    else
    {
        //无小数部分,则补充.00
        [tempStr appendString:@".00"];
    }

    return tempStr;
}

2、金额字符串处理:给金额插入逗号分隔,保留两位有效数字

+ (NSString*)insertCommaInNumStr:(NSString*)number
{
    if ([StaticTools isEmptyString:number] || [number isEqualToString:@"(null)"])
    {
        return @"";
    }

    NSString *valueStr = [number stringByReplacingOccurrencesOfString:@"," withString:@""];
    NSMutableString *resultStr = [NSMutableString stringWithFormat:@"%.2f",[valueStr doubleValue]];
    
    BOOL bellowZearo = NO;

    if ([valueStr doubleValue]<0)
    {
        bellowZearo = YES;
        [resultStr replaceCharactersInRange:NSMakeRange(0, 1) withString:@""];
    }

    int count = ([resultStr length]-1)/3-2;
    int mod = [resultStr length] % 3 == 0 ? 3 : [resultStr length]%3;
    
    for (int i=0; i<=count; i++)
    {
        [resultStr insertString:@"," atIndex:mod + 3*(count-i)];
    }
    
    if (bellowZearo)
    {
        [resultStr insertString:@"-" atIndex:0];
    }
    
    return resultStr;
}

3、设置卡号的显示格式

/*
 设置卡号的显示形式,除了前6位和后四位,其余用"*"代替
 cardNoStr为传入的卡号
 */
+ (NSString *)setCardNoAsterisk:(NSString *)cardNoStr
{
    if (!cardNoStr || [cardNoStr isEqual:[NSNull null]])
    {
        return @"";
    }

    if (cardNoStr.length >13)
    {
        NSString *asterisk = @"";

        for (int i = 0; i < cardNoStr.length - 10; i++)
        {
            asterisk = [asterisk stringByAppendingString:@"*"];
        }

        NSRange range = NSMakeRange(6, cardNoStr.length -10);
        cardNoStr = [cardNoStr stringByReplacingCharactersInRange:range withString:asterisk];
    }

    return cardNoStr;
}

你可能感兴趣的:(格式化字符串)