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.-floatValueand-doubleValueare merely quick-and-easy temporary fixes, but they fail in bad ways. For example:-floatValueis unable to distinguish between a proper number (@"0") and an invalid one (@"abc").NSNumberFormatter, on the other hand, will give younilif it can't parse it, and anNSNumberif it can. It also takes things like currency symbols, region-specific decimal and thousands separators, and the user's locale into account.-floatValueand friends do not.See this related question for more info: How to convert an NSString into an NSNumber