[英]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.