2013年2月1日金曜日

文字列から数字に変換したい

NSStringクラスには、格納した文字列をプリミティブな型に変換するメソッドが登録されています。

// double型に変換
- (double) doubleValue;

// float型に変換
- (float) floatValue;

// int型に変換
- (int) intValue;

// NSInteger型に変換
- (NSInteger) integerValue;

// long long型に変換
- (long long) longLongValue;

// BOOL型に変換
- (BOOL) boolValue;  

例えば、以下の様な文字列を変換した場合はどうなるでしょう。
NSString *temp = @"1.23";

この様に変換されます。
NSString *temp = @"1.23";
[temp doubleValue];   // (double)1.23
[temp floatValue];    // (float)1.23
[temp intValue];      // (int)1
[temp integerValue];  // (NSInteger)1
[temp longLongValue]; // (long long)1
[temp boolValue];     // (BOOL)YES


ここで少し数値を上げてみます。
NSString *temp = @"1.78";

この様に変換されます。
NSString *temp = @"1.78";
[temp doubleValue];   // (double)1.78
[temp floatValue];    // (float)1.78
[temp intValue];      // (int)1
[temp integerValue];  // (NSInteger)1
[temp longLongValue]; // (long long)1
[temp boolValue];     // (BOOL)YES

まぁ、自動で四捨五入される様な仕様にはなってないですね^^;
勝手にされても困りますが。。。


次に文字列でやってみます。
NSString *temp = @"aaa";
[temp doubleValue];   // (double)0
[temp floatValue];    // (float)0
[temp intValue];      // (int)0
[temp integerValue];  // (NSInteger)0
[temp longLongValue]; // (long long)0
[temp boolValue];     // (BOOL)NO

ゼロになりますので、判断する必要が出た時はこれで良さそうですね。


数値混入でやってみます。
NSString *temp = @"a11";
[temp doubleValue];   // (double)0
[temp floatValue];    // (float)0
[temp intValue];      // (int)0
[temp integerValue];  // (NSInteger)0
[temp longLongValue]; // (long long)0
[temp boolValue];     // (BOOL)NO


数値混入で、先ほどの順序逆転でやってみます。
NSString *temp = @"11a";
[temp doubleValue];   // (double)11
[temp floatValue];    // (float)11
[temp intValue];      // (int)11
[temp integerValue];  // (NSInteger)11
[temp longLongValue]; // (long long)11
[temp boolValue];     // (BOOL)YES

どうやら、解釈の及ぶ所までは頑張って変換してくれるみたいです。

0 件のコメント:

コメントを投稿