在目标 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_;
I have a parser returning some string value I'd like to use as parameter for my class instance initialisation.
I have a method asking two NSString and a float value, but I can't convert the string to float, here is my code:
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];
in the .h
- (id) addCurrencyWithFrom: (NSString *) from_ andTo:(NSString *) to_ andRate:(float *) float_;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不不不不不不不不不。
使用
NSNumberFormatter
。 这就是它存在的原因。-floatValue
和-doubleValue
只是快速简单的临时修复,但它们会以糟糕的方式失败。例如:-floatValue
无法区分正确的数字 (@"0"
) 和无效的数字 (@"abc"
) 。另一方面,如果
NSNumberFormatter
无法解析它,它会给你nil
,如果可以的话,会给你一个NSNumber
。它还考虑了货币符号、特定于区域的小数点和千位分隔符以及用户的区域设置等因素。-floatValue
和朋友们没有。有关详细信息,请参阅此相关问题:如何转换NSString 转换为 NSNumber
No no no no no no no no no.
Use an
NSNumberFormatter
. This is why it exists.-floatValue
and-doubleValue
are merely quick-and-easy temporary fixes, but they fail in bad ways. For example:-floatValue
is unable to distinguish between a proper number (@"0"
) and an invalid one (@"abc"
).NSNumberFormatter
, on the other hand, will give younil
if it can't parse it, and anNSNumber
if it can. It also takes things like currency symbols, region-specific decimal and thousands separators, and the user's locale into account.-floatValue
and friends do not.See this related question for more info: How to convert an NSString into an NSNumber
尝试:
此外,传递 NSNumber* 而不是 float 不会给您带来预期的结果。
Try:
Also, passing an NSNumber* instead of a float will not give you the results that you are expecting.