2012-03-09 6 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に変換します。 –

+1

http://stackoverflow.com/questions/4791470/convert-nsstring-to-nsinteger – bdparrish

+1

@ user993223「文字列を整数に変換する」とはどういう意味ですか?達成したい結果は何ですか? –

答えて

2

あなたは45.1を予想した場合、間違った二つのものがあります:

  1. 45.1integerではありませんが。値を読み取るには、floatValueを使用する必要があります。

  2. 45,1(カンマに注意してください)は有効な浮動小数点数ではありません。一部のロケールで45,1が有効です(1,000.25の代わりに1 000,25をフレンチで使用しています)。を読む前に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のような整数形式と同じ結果が必要です。 –

+0

45,1は整数ではありません。 – HelmiB

+1

'45.1'または' 45,1'は**小数点以下**の値です。それらを**整数**に格納することは不可能です。整数は全体の値です。小数点の値を整数にする唯一の方法は、値を四捨五入することです:結果は '45'になります。 –

0

多くの質問を読んでから、私はあなたが望むものを理解できると思います。

出発点があるように思わ:

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

と現在の終点は次のとおりです。

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

しかし、それはあなたがまだ45,1

をプリントアウトしたいようですマイこれは、arrayyyyと呼ばれる2つの文字列[@ "45"、@ "1"]の配列を持ち、両方の値を整数として出力したいと考えています。これがそう、私はあなたが欲しいと思うものですされている場合:

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

、アレイ内の少なくとも2つの文字列が存在しない場合、これは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 
関連する問題