这里是一个很长时间的潜伏者(但仍然是主要吸引程序员)。我环顾四周寻找答案,找不到任何答案。将数组字符串对象转换为浮点数
我想从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
)。
在此先感谢您的帮助。
可可的格式化器是敏感的混蛋。如果它不喜欢/识别格式字符串的一个字符,它只会保留并在每次调用中返回'nil'(0,0.0,NULL等)。如果你只需要将一个字符串转换为一个浮点数,可以考虑使用C stdlib函数'strtod()'。 – 2013-12-15 22:29:41
如果这些值是浮动的,为什么他们在plist中串起来?你可以把数字放在plist中。 – rmaddy