如何在Objective-C中将字符串转换成浮点数?
我正试图对从JSON返回的一些字符串进行乘法运算:
float subTotal = [[[[purchaseOrderItemsJSON objectAtIndex:i] objectAtIndex:j] objectForKey:@"Price"] floatValue];
NSLog(@"%@", subTotal);
在控制台中我得到了:(null)
。我知道数组里面有一个有效的字符串,因为我已经使用它来显示标签的值。
如何在Objective-C中将字符串转换成浮点数?
我正试图对从JSON返回的一些字符串进行乘法运算:
float subTotal = [[[[purchaseOrderItemsJSON objectAtIndex:i] objectAtIndex:j] objectForKey:@"Price"] floatValue];
NSLog(@"%@", subTotal);
在控制台中我得到了:(null)
。我知道数组里面有一个有效的字符串,因为我已经使用它来显示标签的值。
your_float = [your_string floatValue];
编辑:
尝试这个:
NSLog(@"float value is: %f", your_float);
正确的做法是
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
float value = [numberFormatter numberFromString:@"32.12"].floatValue;
value
将会是 0.0
, 正如之前某个回答中 @user111823 在评论中提到的。如果您总是期望使用 .
作为分隔符,则需要设置 numberFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
。 - thetrutz