5

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_;
mskfisher
  • 3,291
  • 4
  • 35
  • 48
Michele
  • 681
  • 3
  • 16
  • 27
  • `but I can't convert the string to float` - Do you mean here the string is NSString or a C String ? – Mahesh Jan 28 '11 at 17:37
  • As a side note, if you're doing a currency converter, you might be interested in checking out: https://github.com/davedelong/DDUnitConverter It has a currency converter that pulls data from the IMF. – Dave DeLong Jan 28 '11 at 18:04
  • 2
    Note also that you'll really really want to avoid floats when doing anything with currency. Floats are remarkable in their ability to not be able to accurately represent or compute relatively small values. Doubles are significantly better. – bbum Jan 28 '11 at 18:41

3 Answers3

19

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

Community
  • 1
  • 1
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
7
float f = [yourStringObject floatValue];
David
  • 9,635
  • 5
  • 62
  • 68
1

Try:

double f = [from_ doubleValue];
double t = [to_ doubleValue];

Also, passing an NSNumber* instead of a float will not give you the results that you are expecting.

Mark
  • 6,108
  • 3
  • 34
  • 49