Ios 将数组字符串对象转换为浮点数

Ios 将数组字符串对象转换为浮点数,ios,objective-c,arrays,Ios,Objective C,Arrays,长期潜伏者(但仍然是最差劲的程序员)在这里。我四处寻找这个问题的答案,却找不到任何答案 我试图从plist中读取数组,然后将这些对象从字符串转换为浮点 我现在正在尝试的代码声明了一个NSNumberFormatter,并尝试读入其中并将其转换为浮点。它不工作,NSLog始终显示这些值的0 下面是我的代码,我正在使用它(成功地)从Plist读取数组,并(未成功地)将其字符串转换为浮点数: //Find the Plist and read in the array: NSArray *paths

长期潜伏者(但仍然是最差劲的程序员)在这里。我四处寻找这个问题的答案,却找不到任何答案

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

我现在正在尝试的代码声明了一个
NSNumberFormatter
,并尝试读入其中并将其转换为浮点。它不工作,
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;
所以我的问题是:

如何将数组中存储的对象从其当前字符串转换为更可用的浮动?理想情况下,我希望使用循环在一行中完成这一切,但也很乐意为每个循环设置单独的
cgloats
(例如
readVol


提前感谢您的帮助。

NSNumberFormatterDecimalStyle的问题可能是它是本地语言环境 依赖的。例如,对于我的德语语言环境,数字
1.234,56
被转换 正确,但无法转换
1234.56
。 因此,您可以设置一个已定义的区域设置来解决此问题:

NSNumberFormatter *format = [[NSNumberFormatter alloc] init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
[format setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
或者,
NSString
有一个提供字符串内容的
floatValue
方法 作为
浮点数

float f = [fileArray[0] floatValue];
由于
CGFloat
可以是
float
double
,具体取决于体系结构, 为了安全起见,您可能需要使用
doubleValue

CGFloat f = [fileArray[0] doubleValue];

Cocoa中的格式化程序是敏感的混蛋。如果它不喜欢/不识别格式字符串中的一个字符,它只会跳出并在每次调用时返回
nil
(0、0.0、NULL等)。如果你只需要把一个字符串转换成一个浮点,考虑使用C STDLIB函数<代码> Strutd()<代码>。如果这些值是浮点数,为什么它们是PLIST中的字符串?你可以在plist中输入数字。太棒了,谢谢!我要把这个接上。一位CS朋友建议我也在谷歌上搜索“typecasting”,所以需要尝试一下;为我备受困扰的最终项目创造了奇迹。:-)