在Objective-C中将字符串转换为float

Sle*_*lee 27 objective-c

如何在Objective-C中将字符串转换为浮点数?

我试图将我从JSON回来的几个字符串相乘:

float subTotal = [[[[purchaseOrderItemsJSON objectAtIndex:i] objectAtIndex:j] objectForKey:@"Price"] floatValue];

NSLog(@"%@",subTotal);
Run Code Online (Sandbox Code Playgroud)

这给了我:(null)在控制台中.我知道有一个有效的字符串来自该数组,因为我已经使用它来在标签中显示它的值.

Ram*_*ngh 71

your_float = [your_string floatValue];
Run Code Online (Sandbox Code Playgroud)

编辑:

试试这个:

  NSLog(@"float value is: %f", your_float);
Run Code Online (Sandbox Code Playgroud)

  • 如文档中所述,请注意格式是非本地化的.在德国,人们使用逗号作为分隔符,即"1,28"与"1.28".floatValue在这种情况下不起作用. (3认同)

Mar*_*usz 17

这样做的正确方法是

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

float value = [numberFormatter numberFromString:@"32.12"].floatValue;
Run Code Online (Sandbox Code Playgroud)

  • :-) +1试图移动海洋. (4认同)