How to check if NSString is numeric or not [duplicate]

对着背影说爱祢 提交于 2019-12-17 16:32:59

问题


Possible Duplicate:
iphone how to check that a string is numeric only

I have one NSString, then i want check the string is number or not.

I mean

NSString *val = @"5555" ;

if(val isNumber ){
  return true;
}else{
  retun false;
}

How can I do this in Objective C?


回答1:


Use [NSNumberFormatter numberFromString: s]. It returns nil if the specified string is non-numeric. You can configure the NSNumberFormatter to define "numeric" for your particular scenario.


#import <Foundation/Foundation.h>

int
main(int argc, char* argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSLocale *l_en = [[NSLocale alloc] initWithLocaleIdentifier: @"en_US"];
    NSLocale *l_de = [[NSLocale alloc] initWithLocaleIdentifier: @"de_DE"];
    NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
    [f setLocale: l_en];

    NSLog(@"returned: %@", [f numberFromString: @"1.234"]);

    [f setAllowsFloats: NO];
    NSLog(@"returned: %@", [f numberFromString: @"1.234"]);

    [f setAllowsFloats: YES];
    NSLog(@"returned: %@", [f numberFromString: @"1,234"]);

    [f setLocale: l_de];
    NSLog(@"returned: %@", [f numberFromString: @"1,234"]);

    [l_en release];
    [l_de release];
    [f release];
    [pool release];
}



回答2:


You could use rangeOfCharacterFromSet::

@interface NSString (isNumber)
-(BOOL)isInteger;
@end

@interface _IsNumber
+(void)initialize;
+(void)ensureInitialization;
@end

@implementation NSString (isNumber)
static NSCharacterSet* nonDigits;
-(BOOL)isInteger {
    /* bit of a hack to ensure nonDigits is initialized. Could also 
       make nonDigits a _IsNumber class variable, rather than an 
       NSString class variable.
     */
    [_IsNumber ensureInitialization];
    NSRange nond = [self rangeOfCharacterFromSet:nonDigits];
    if (NSNotFound == nond.location) {
        return YES;
    } else {
        return NO;
    }
}
@end

@implementation _IsNumber
+(void)initialize {
    NSLog(@"_IsNumber +initialize\n");
    nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
}
+(void)ensureInitialization {}
@end


来源:https://stackoverflow.com/questions/2020360/how-to-check-if-nsstring-is-numeric-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!