Extracting digits from integer and decimal parts of a double
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.
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]);
I'd convert it to a string (using +[NSString stringWithFormat:]
) and then scan out the numbers using rangeOfCharactersInSet:
or an NSScanner
.
精彩评论