user3105483
user3105483

Reputation: 3

Convert array string objects to floats

Longtime lurker (but still majorly sucky programmer) here. I've looked around for the answer to this and couldn't find any.

I'm trying to read an array from a plist, and then turn those objects from strings to floats.

The code that I'm trying right now declares an NSNumberFormatter, and tries to read in and convert to a float there. It's not working, the NSLog always shows a 0 for those values.

Here's my code that I'm using to (successfully) read-in the array from Plist, and (not successfully) convert its strings to floats:

//Find the Plist and read in the array:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
NSString *filePath =  [docDirectory stringByAppendingPathComponent:kFilename];
//Working up til here, the NSLog correctly shows the values of the array
NSArray *fileArray = [[NSArray alloc] initWithContentsOfFile:filePath];

//Turn object in array from string to float
NSNumberFormatter *format = [[NSNumberFormatter alloc] init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *readinVol = [format numberFromString: fileArray [0]]; 
//This line not working, I believe- intended to read-in as an NSNumber, 
//and then convert to float below:
CGFloat readVol = [readinVol floatValue] * _volFloat;

So my question is:

How can I turn my objects stored in the array from their current strings into more usable floats? I'd ideally like to do this all in one line with a loop, but would also be happy setting up separate CGFloats for each (such as readVol).

Thanks in advance for any help.

Upvotes: 0

Views: 891

Answers (1)

Martin R
Martin R

Reputation: 539745

The problem with NSNumberFormatterDecimalStyle might be that it is locale dependent. For example, with my German locale, the number 1.234,56 is converted correctly, but 1234.56 cannot be converted. So you could set a defined locale to solve the problem:

NSNumberFormatter *format = [[NSNumberFormatter alloc] init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
[format setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];

Alternatively, NSString has a floatValue method that gives the contents of the string as a float:

float f = [fileArray[0] floatValue];

Since CGFloat can be float or double, depending on the architecture, you may want to use doubleValue to be on the safe side:

CGFloat f = [fileArray[0] doubleValue];

Upvotes: 1

Related Questions