iOS---金额格式化NSNumberFormatter,NSDecimalNumber

+(NSString *)fomartNumber:(id)idNumber{
    if (idNumber == nil) {
        return @"0.00";
    }
    if ([idNumber isKindOfClass:[NSString class]]&&[idNumber isEqualToString:@""]) {
        return @"0.00";
    }
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    formatter.maximumFractionDigits = 4;
    formatter.minimumFractionDigits = 2;
    if ([idNumber isKindOfClass:[NSString class]]) {
         1:金额保留2到4位小数 格式化

        NSString *tempStr = (NSString *)idNumber;
        [tempStr stringByReplacingOccurrencesOfString:@"," withString:@""];
        
        NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithString:tempStr];
        return [formatter stringFromNumber:decimalNumber];
    }
    if ([idNumber isKindOfClass:[NSNumber class]]) {
         return [formatter stringFromNumber:idNumber];
    }
    return @"0.00";
}
2:判断纯数字
//^[0-9]*$
+ (BOOL)isNumText:(NSString *)str{
    NSString * regex        = @"^[0-9]*$";
    NSPredicate * pred      = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch            = [pred evaluateWithObject:str];
    return isMatch;
}

3:提取字符串中的数字  如果有多个小数点可能会出问题
///一般还是让服务器返回数值类型
 NSString *orginPricePureStr = [[_entity.goods_price componentsSeparatedByCharactersInSet:[[NSCharacterSet characterSetWithCharactersInString:@"01234567890."] invertedSet]] componentsJoinedByString:@""];

你可能感兴趣的:(iOS---金额格式化NSNumberFormatter,NSDecimalNumber)