在目标c中浮动的字符串 [英] String to float in objective c

查看:145
本文介绍了在目标c中浮动的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个方法要求两个NSString和一个浮点数值,但我不能将字符串转换为浮动,这是我的代码:

$ p $ N $ ] 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_和To:(NSString *)to_ andRate:(float *)float_; 


解决方案

No no no no no no no no no no。



使用 NSNumberFormatter 。这就是为什么它存在。 -floatValue -doubleValue 只是快捷方便的临时修复,但是它们会以不好的方式失败。例如:

  NSLog(@%f,[@123floatValue]); //日志123.0000 
NSLog(@%f,[@abcfloatValue]); //日志0.0000
NSLog(@%f,[@0floatValue]); //日志0.0000
NSLog(@%f,[@42floatValue]); // log 42.0000
NSLog(@%f,[@42xfloatValue]); // log 42.0000

-floatValue is unable ( @0)和一个无效的( @abc)区分。 / p>

NSNumberFormatter ,另一方面会给你 nil 如果它不能解析它,并且如果可以的话 NSNumber 。它还需要像货币符号,区域特定的小数和千位分隔符以及用户的区域设置。 -floatValue 和朋友不需要。



有关详细信息,请参阅以下相关问题:

$ b $

b

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_;

解决方案

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:

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 is unable to distinguish between a proper number (@"0") and an invalid one (@"abc").

NSNumberFormatter, on the other hand, will give you nil if it can't parse it, and an NSNumber 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

这篇关于在目标c中浮动的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆