31

How do I convert a string to a float in Objective-C?

I am trying to multiply a couple of strings I am getting back from JSON:

float subTotal = [[[[purchaseOrderItemsJSON objectAtIndex:i] objectAtIndex:j] objectForKey:@"Price"] floatValue];

NSLog(@"%@", subTotal);

This gives me: (null) in the console. I know that there is a valid string coming out of that array because I am already using it to display its value in a label.

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
Slee
  • 27,498
  • 52
  • 145
  • 243

2 Answers2

75
your_float = [your_string floatValue];

EDIT:

try this:

  NSLog(@"float value is: %f", your_float);
Ramadheer Singh
  • 4,124
  • 4
  • 32
  • 44
  • float subTotal = [[[[purchaseOrderItemsJSON objectAtIndex:i] objectAtIndex:j] objectForKey:@"Price"] floatValue]; NSLog(@"%@",subTotal); This gives me a (null) on console. I know there is a string value in there. – Slee Jul 08 '10 at 02:42
  • 1
    @Max, Can you try to print that string, and paste it here? – Ramadheer Singh Jul 08 '10 at 04:00
  • it is: 3399 and the output ends up being: (null) – Slee Jul 08 '10 at 11:43
  • I am a dope - @"%@", I'll leave it at that – Slee Jul 08 '10 at 16:51
  • 4
    As stated in the documentation, beware that the format is non-localized. In Germany people use a comma as separator, i.e. "1,28" vs. "1.28". floatValue will not work in this case. –  Nov 24 '11 at 12:50
18

The proper way of doing this is

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;

float value = [numberFormatter numberFromString:@"32.12"].floatValue;
Mariusz
  • 1,409
  • 12
  • 25
  • 4
    :-) +1 for trying to move the ocean. – Benjohn Dec 02 '14 at 23:05
  • 1
    Beware of the locale! With German locale the `value` will be `0.0` as mentioned also by @user111823 in a comment for a previous answer. You need to set `numberFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];`, if you are always expecting `.` as separator. – thetrutz Apr 17 '18 at 22:06