iOS判断一个字符串是否全是数字

0.46字数 173阅读 805

最近有一个需求,需要判断后台返回的字段是否全部是数字.首先想到的事正则,还有就是NSCharacterSet,但是NSCharacterSet不怎么会用.(等过两天,我就写文章将这个).
于是就上网查了查.果然还有别的方法.
大概也就三种方法:

  1. 正则.
- (BOOL) judgeIsNumberByRegularExpressionWith:(NSString *)str
{
   if (str.length == 0) {
        return NO;
    }
    NSString *regex = @"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if ([pred evaluateWithObject:str]) {
        return YES;
    }
    return NO;
}
  1. 使用NSCharacterSet.
    stringByTrimmingCharactersInSet函数可以把我们指定的特殊字符过滤掉,进而判断剩下的内容,如果是空,说明全部是数字.
 - (BOOL)theStringIsAllNumbers:(NSString *)str {
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(str.length > 0) {
        return NO;
    }
    return YES;
}

3.用NSScanner类来判断
NSScanner是一个类,用于在字符串中扫描指定的字符。
想详细了解,可以参考NSScanner类条件判断利器详解

- (BOOL) theStringIsAllNumbers:(NSString*)str{
    NSScanner* scan = [NSScanner scannerWithString: str];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}
- (BOOL)isNum:(NSString *)checkedNumString {
    NSCharacterSet *str=[[NSCharacterSet characterSetWithCharactersInString:@".1234567890-"] invertedSet];
    NSString *filter=[[checkedNumString componentsSeparatedByCharactersInSet:str] componentsJoinedByString:@""];
    BOOL isNum = [checkedNumString isEqualToString:filter];
    return isNum;
}

-(NSString *)conversionDisplayContent:(NSString *)content{
    if ([self isNum:content]) {  //全是数字
        NSString *str =[self decimalwithFloatString:content];
        return [NSString stringWithFormat:@"%.2f",[str floatValue]];
    } else {
        return content;
    }
}

- (NSString *)decimalwithFloatString:(NSString *)floatV{
    NSDecimalNumberHandler *behavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    NSDecimalNumber *numResult1 = [NSDecimalNumber decimalNumberWithString:floatV];
    return [NSString stringWithFormat:@"%@",[numResult1 decimalNumberByRoundingAccordingToBehavior:behavior]];
}

推荐阅读更多精彩内容