Finding out whether a string is numeric or not

前端 未结 18 1558
一个人的身影
一个人的身影 2020-12-07 15:24

How can we check if a string is made up of numbers only. I am taking out a substring from a string and want to check if it is a numeric substring or not.

NSS         


        
相关标签:
18条回答
  • 2020-12-07 15:51

    Swift 3 solution if need to verify that the string has only digits:

    CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: myString))
    
    0 讨论(0)
  • 2020-12-07 15:51

    to be clear, this functions for integers in strings.

    heres a little helper category based off of John's answer above:

    in .h file

    @interface NSString (NumberChecking)
    
    +(bool)isNumber:(NSString *)string;
    
    @end
    

    in .m file

    #import "NSString+NumberChecking.h"
    
    @implementation NSString (NumberChecking)
    
    +(bool)isNumber {
        if([self rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location == NSNotFound) {
            return YES;
        }else {
            return NO;
        }
    }
    
    @end
    

    usage:

    #import "NSString+NumberChecking.h"
    
    if([someString isNumber]) {
        NSLog(@"is a number");
    }else {
        NSLog(@"not a number");
    }
    
    0 讨论(0)
  • Swift extension :

    extension NSString {
    func isNumString() -> Bool {
        let numbers = NSCharacterSet(charactersInString: "0123456789.").invertedSet
        let range = self.rangeOfCharacterFromSet(numbers).location
        if range == NSNotFound {
            return true
        }
        return false
    }  }
    
    0 讨论(0)
  • 2020-12-07 15:58

    I'd suggest using the numberFromString: method from the NSNumberFormatter class, as if the number is not valid, it will return nil; otherwise, it will return you an NSNumber.

    NSNumberFormatter *nf = [[[NSNumberFormatter alloc] init] autorelease];
    BOOL isDecimal = [nf numberFromString:newString] != nil;
    
    0 讨论(0)
  • 2020-12-07 15:59

    When you have digits that are from mixed languages, that use (or don't) the 0-9 digits formats, you will need to run a regex that will look for any number, next thing is to convert all digits to be 0-9 format (if you need the actual value):

    // Will look for any language digits
    let regex = try NSRegularExpression(pattern: "[^[:digit:]]", options: .caseInsensitive)
    let digitsString = regex.stringByReplacingMatches(in: string,
                                                             options: NSRegularExpression.MatchingOptions(rawValue: 0),
                                                             range: NSMakeRange(0, string.count), withTemplate: "")
    // Converting the digits to be 0-9 format
    let numberFormatter = NumberFormatter()
    numberFormatter.locale = Locale(identifier: "EN")
    let finalValue = numberFormatter.number(from: digitsString)
    
    if let finalValue = finalValue {
      let actualValue = finalValue.doubleValue
    }
    
    0 讨论(0)
  • 2020-12-07 16:03

    Here's one way that doesn't rely on the limited precision of attempting to parse the string as a number:

    NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    if ([newString rangeOfCharacterFromSet:notDigits].location == NSNotFound)
    {
        // newString consists only of the digits 0 through 9
    }
    

    See +[NSCharacterSet decimalDigitCharacterSet] and -[NSString rangeOfCharacterFromSet:].

    0 讨论(0)
提交回复
热议问题