[英]String to float in objective c
我有一個解析器返回一些字符串值,我想用作我的類實例初始化的參數。
我有一個方法詢問兩個NSString和一個浮點值,但我不能將字符串轉換為浮點數,這是我的代碼:
NSString *from = [[NSString alloc] initWithString:@"EUR"];
NSString *to = [[NSString alloc] initWithString:[attributeDict objectForKey:@"currency"]];
NSNumber *rate = [[NSNumber alloc] initWithFloat:[[attributeDict objectForKey:@"rate"] doubleValue]];
currency = [[Currency init] alloc];
[currency addCurrencyWithFrom:from andTo:to andRate:rate];
在.h
- (id) addCurrencyWithFrom: (NSString *) from_ andTo:(NSString *) to_ andRate:(float *) float_;
不不不不不不不不不。
使用NSNumberFormatter
。 這就是它存在的原因 。 -floatValue
和-doubleValue
只是快速簡便的臨時修復,但它們以不好的方式失敗。 例如:
NSLog(@"%f", [@"123" floatValue]); //logs 123.0000
NSLog(@"%f", [@"abc" floatValue]); //logs 0.0000
NSLog(@"%f", [@"0" floatValue]); //logs 0.0000
NSLog(@"%f", [@"42" floatValue]); //logs 42.0000
NSLog(@"%f", [@"42x" floatValue]); //logs 42.0000
-floatValue
無法區分正確的數字( @"0"
)和無效的數字( @"abc"
)。
NSNumberFormatter
,而另一方面,也會給你nil
,如果它不能解析它,和NSNumber
,如果它可以。 它還會考慮貨幣符號,區域特定的小數和千位分隔符以及用戶的區域設置。 -floatValue
和朋友沒有。
有關更多信息,請參閱此相關問題: 如何將NSString轉換為NSNumber
float f = [yourStringObject floatValue];
嘗試:
double f = [from_ doubleValue];
double t = [to_ doubleValue];
此外,傳遞NSNumber *而不是浮點數將無法獲得您期望的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.