Slee
Slee

Reputation: 28268

Convert string to float in Objective-C

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.

Upvotes: 31

Views: 58400

Answers (2)

Mariusz
Mariusz

Reputation: 1409

The proper way of doing this is

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

float value = [numberFormatter numberFromString:@"32.12"].floatValue;

Upvotes: 18

Ramadheer Singh
Ramadheer Singh

Reputation: 4234

your_float = [your_string floatValue];

EDIT:

try this:

  NSLog(@"float value is: %f", your_float);

Upvotes: 76

Related Questions