laplace's demon

Archive for February, 2012

NSString isNumeric

by on Feb.17, 2012, under Uncategorized

I wanted to know if the string object has only numeric values in it (only integers in my case). Although there is intValue message in the NSString object, it will only give the int conversion of the object. So I come up with the following category implementation:

@interface NSString (Numeric)

- (BOOL)isNumeric;

@end

@implementation NSString (Numeric)

- (BOOL)isNumeric
{
    if (self == 0)
        return YES;

    NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
    [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];

    // set YES if you want to use floats as numeric
    [formatter setAllowsFloats:NO];

    NSNumber* number = [formatter numberFromString:self];

    return (number) ? YES : NO;
}

@end

And following is the test cases for it.

#import "NSStringNumericTest.h"
#import "NSString+Numeric.h"

@implementation NSStringNumericTest

// All code under test must be linked into the Unit Test bundle
- (void)testIsNumeric
{
    NSString* numeric = @"21";
    STAssertTrue([numeric isNumeric], @"number is numeric");

    NSString* numeric2 = @"0";
    STAssertTrue([numeric2 isNumeric], @"number is numeric");

    NSString* numeric3 = @"21,21";
    STAssertFalse([numeric3 isNumeric], @"number is not numeric");

    NSString* numeric4 = @"asdasd";
    STAssertFalse([numeric4 isNumeric], @"number is not numeric");
}

@end

In my case, I don’t want to allow floats as numeric. You can always modify the class implementation according to your needs.

Leave a Comment more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...