从双精度整数和小数部分中提取数字 [英] Extracting digits from integer and decimal parts of a double

查看:166
本文介绍了从双精度整数和小数部分中提取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用Cocoa Touch(需要在iPhone上运行)从ObjectiveC中的双精度数字中提取数字的最优雅方法是什么:



让我们假设您有一个double:1.423



您将如何获取组成double的每个 1, 4, 2, 3几个变量?



最后,我想得到如下内容:

  
NSLog (@这里是数字:%d,%d%d%d,一,二,三,四);



一个变量应为1



两个变量应为4



三个变量应为2



四个变量应为3



任何实现此目标的建议以一种很好的方式使用ObjectiveC / cocoa Touch?



谢谢。

解决方案

这是我为您准备的东西

  @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 ++;
}
返回数字;
}

@end

然后在您的代码中执行像这样的东西:

  NSArray * myDigits = [[NSNumber numberWithDouble:1.423] arrayOfStringDigits]; 
NSLog(@ Array =>%@,myDigits);
NSLog(@此处为数字:%@,%@%@%@,
[myDigits objectAtIndex:0],
[myDigits objectAtIndex:1],
[myDigits objectAtIndex:2],
[myDigits objectAtIndex:3]);


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]);

这篇关于从双精度整数和小数部分中提取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆