Mic*_*ele 5 floating-point objective-c nsnumber nsstring
我有一个解析器返回一些字符串值,我想用作我的类实例初始化的参数.
我有一个方法询问两个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];
Run Code Online (Sandbox Code Playgroud)
在.h
- (id) addCurrencyWithFrom: (NSString *) from_ andTo:(NSString *) to_ andRate:(float *) float_;
Run Code Online (Sandbox Code Playgroud)
Dav*_*ong 18
不不不不不不不不不.
用一个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
Run Code Online (Sandbox Code Playgroud)
-floatValue无法区分正确的数字(@"0")和无效的数字(@"abc").
NSNumberFormatter另一方面,nil如果它无法解析它,它会给你,如果可以的NSNumber话.它还会考虑货币符号,区域特定的小数和千位分隔符以及用户的区域设置. -floatValue和朋友不.
有关更多信息,请参阅此相关问题: 如何将NSString转换为NSNumber