天天看點

Objective-C中NSString轉NSNumber的方法

在Objective-C中,以數字格式組成的字元串經常需要轉換為NSNumber對象後再使用。

例如有一個字元串對象@"111.22",需要轉為NSNumber對象,最簡單的方法就是這樣:[NSNumber numberWithFloat:[@"111.22" floatValue]]。

這個方法先使用NSString的floatValue方法将字元串轉成float,再使用NSNumber的numberWithFloat方法将結果轉成NSNumber。但它有一個前提條件,就是輸入的字元串一定要以數字組成。如果發現有非數字字元,則直接導緻程式出錯。是以,它需要事先判斷,保證字元串能轉成NSNumber。

根據新的要求,将轉換操作過程修改一下,代碼如下所示:

    NSString *[email protected]"224.34129";

    id result;

    NSNumberFormatter *f = [[NSNumberFormatter alloc] init];

    if ([f numberFromString:ss])

    {

        result=[NSNumber numberWithFloat:[ss floatValue]];

    }

    else

    {

        result=ss;

    }

    NSLog(@"%.2f",[result floatValue]);

如此一改,功能倒是沒問題了,隻是看上去有一些累贅。我們知道,代碼越簡潔,出bug的機率就越低,代碼也越顯得優雅。再做修改,如下所示:

    NSString *[email protected]"224.34129";

    id result;

    result=[f numberFromString:ss];

    if(!(result))

    {

        result=ss;

    }

    NSLog(@"%.2f",[result floatValue]);

還有其他的轉換函數,如

1、字元串拼接

 NSString *newString = [NSString stringWithFormat:@"%@%@",tempA,tempB];

2、字元串轉int

int intString = [newString intValue];

3、int轉字元串

NSString *stringInt = [NSString stringWithFormat:@"%d",intString];

4、字元串轉float

 float floatString = [ newString floatValue];

5、float轉字元串

NSString *stringFloat = [NSString stringWithFormat:@"%f",intString];

通過這些轉換操作,可以了解NSNumber、NSString、float三個類型的關系和轉換方法。int/float是Objective-C的原始類型,而NSNumber和NSString則是類。