2012-03-09 50 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 
相關問題