2013-12-15 228 views
0

这里是一个很长时间的潜伏者(但仍然是主要吸引程序员)。我环顾四周寻找答案,找不到任何答案。将数组字符串对象转换为浮点数

我想从plist中读取数组,然后将这些对象从字符串转换为浮点数。

我正在尝试的代码现在声明NSNumberFormatter,并尝试读入并转换为float。它不工作,NSLog总是显示为0这些值。

这里是我的代码,我使用(成功)从Plist读入阵,和(没有成功)转化的字符串彩车:

//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; 

所以我的问题是:

如何将存储在数组中的对象从当前的字符串转换为更多可用的浮点数?理想情况下,我喜欢在一个循环中完成所有操作,但也很乐意为每个循环设置单独的CGFloats(如readVol)。

在此先感谢您的帮助。

+0

可可的格式化器是敏感的混蛋。如果它不喜欢/识别格式字符串的一个字符,它只会保留并在每次调用中返回'nil'(0,0.0,NULL等)。如果你只需要将一个字符串转换为一个浮点数,可以考虑使用C stdlib函数'strtod()'。 – 2013-12-15 22:29:41

+0

如果这些值是浮动的,为什么他们在plist中串起来?你可以把数字放在plist中。 – rmaddy

回答

1

NSNumberFormatterDecimalStyle的问题可能是它是区域设置 从属。例如,用我的德语语言环境,数字1.234,56正确转换为 ,但无法转换1234.56。 所以,你可以设置一个定义的区域设置来解决这个问题:

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

另外,NSStringfloatValue方法,使该字符串 的内容作为float

float f = [fileArray[0] floatValue]; 

由于CGFloatfloatdouble,具体取决于架构,您可能希望使用doubleValue以确保安全:

CGFloat f = [fileArray[0] doubleValue]; 
+0

超级!你在为苹果工作吗? ;) –

+0

@flexaddicted:No. –

+0

我在开玩笑......无论如何都是很好的答案。 –

相关问题