2012-03-09 48 views
-1
NSString * addString=[arrayyyy componentsJoinedByString:@","]; 

NSLog(@"add string is: %@",addString);// result is: 45,1 

现在我想将上面的字符串转换为整数。如何在iPhone应用程序中将NSString转换为NSInteger?

我已经试过这样:

NSInteger myInt=[addString intValue]; 
//NSLog(@"myInt is: %d",myInt);// result is: 45 
+0

以及,如果结果是45,其转换为int。 [addString intValue]转换为int,[addString integerValue]转换为NSInteger。 – 2012-03-09 13:09:55

+1

http://stackoverflow.com/questions/4791470/convert-nsstring-to-nsinteger – bdparrish 2012-03-09 13:09:59

+1

@ user993223你是什么意思“将字符串转换为整数”?你想达到什么结果? – 2012-03-09 13:10:15

回答

2

如果预期45.1,然后有两个错误:

  1. 45.1不是integer。您将不得不使用floatValue来读取值。

  2. 45,1(注意逗号)不是有效的浮点数。虽然45,1在某些语言环境中有效(即法语1 000,25而不是1,000.25),但在阅读floatValue之前,您必须先将该字符串转换为NSNumberFormatter

// Can't compile and verify this right now, so please bear with me. 
NSString *str = @"45,1"; 
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease]; 
NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"] autorelease]; // lets say French from France 
[formatter setNumberStyle:NSNumberFormatterDecimalStyle]; 
[formatter setLocale:locale]; 
float value = [[formatter numberFromString:str] floatValue]; // value = 45.1 
+0

感谢您的回复,但我希望得到与45,1一样的整数格式的相同结果,请帮助我 – 2012-03-09 14:27:56

+0

45,1不是整数。 – HelmiB 2012-03-09 15:00:39

+1

'45.1'或'45,1'是**小数**值。将它们存储到** integer **是不可能的。整数是整个值。将一个十进制值放入一个整数的唯一方法是对该值进行四舍五入:它会变成“45”。 – 2012-03-09 15:07:43

0

从阅读这个问题很多,我想我可能会明白你想要什么。

的出发点似乎是:

NSLog(@"add string is: %@",addString);// result is: 45,1 

而且目前的终点是:

NSLog(@"myInt is: %d",myInt);// result is: 45 

但似乎你仍然想打印出45,1

我猜测这是你有一个2字符串[@“45”,@“1”]的数组,称为arrayyyy,你想要打印出两个值作为整数。如果是这样,那么我想你想的是:

NSInteger myInt1 = [[arrayyyy objectAtIndex:0] intValue]; 
NSInteger myInt2 = [[arrayyyy objectAtIndex:1] intValue]; 
NSLog(@"add string is: %d,%d",myInt1,myInt2); 

注意这将有NSRangeException可怕的崩溃,如果没有在阵列中至少两个字符串。因此,在最起码你应该做的:

NSInteger myInt1 = -1; 
NSInteger myInt2 = -1; 
if ([arrayyyy length] >0) myInt1 = [[arrayyyy objectAtIndex:0] intValue]; 
if ([arrayyyy length] >1) myInt2 = [[arrayyyy objectAtIndex:1] intValue]; 
NSLog(@"add string is: %d,%d",myInt1,myInt2); 

但即便如此糟糕,因为它假定的-1的防护值将不会出现在实际的数据。

0

试试NSExpression与太数学符号的工作原理(即+-/*):

NSNumber *numberValue = [[NSExpression expressionWithFormat:inputString] expressionValueWithObject:nil context:nil]; 

// do something with numberValue 
相关问题