views:

146

answers:

2

Hi, I would like to know what would be the most elegant approach to extract digits from a double in ObjectiveC using Cocoa Touch (this needs to run on an iPhone):

Let's suppose you have a double : 1.423

How would you get each "1", "4", "2", "3", that compose the double in several variables ?

In the end I would like to get something like :


NSLog(@"here are the digits : %d , %d %d %d ", one, two, three, four);

one variable should be 1

two variable should should be 4

three variable should be 2

four variable should be 3

Any advice to achieve this in a nice way using ObjectiveC / cocoa Touch ?

Thanks.

A: 

I'd convert it to a string (using +[NSString stringWithFormat:]) and then scan out the numbers using rangeOfCharactersInSet: or an NSScanner.

Dave DeLong
+2  A: 

Here is something I whipped up for you real quick.

@interface NSNumber (DigitParsing)

- (NSArray *)arrayOfStringDigits;

@end

@implementation NSNumber (DigitParsing)

- (NSArray *)arrayOfStringDigits {
    NSString *stringNumber = [self stringValue];
    NSMutableArray *digits = [NSMutableArray arrayWithCapacity:[stringNumber length]];
    const char *cstring = [stringNumber cStringUsingEncoding:NSASCIIStringEncoding];
    while (*cstring) {
        if (isdigit(*cstring)) {
            [digits addObject:[NSString stringWithFormat:@"%c", *cstring]];
        }
        cstring++;
    }
    return digits;
}

@end

Then in your code, do something like this:

NSArray *myDigits = [[NSNumber numberWithDouble:1.423] arrayOfStringDigits];
NSLog(@"Array => %@", myDigits);
NSLog(@"here are the digits : %@ , %@ %@ %@ ", 
      [myDigits objectAtIndex:0], 
      [myDigits objectAtIndex:1], 
      [myDigits objectAtIndex:2], 
      [myDigits objectAtIndex:3]);
bstahlhood
Hi, thanks for taking time to share this. I didn't known the isdigit that is a standard C function that's right ? :/ I'll give a try to that one thanks !
yonel
Did this work out for you? If it did, can you mark this the answer?
bstahlhood