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

发布于 2024-09-08 03:04:53 字数 304 浏览 1 评论 0原文

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

我正在尝试乘以从 JSON 返回的几个字符串:

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

NSLog(@"%@", subTotal);

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

How do I convert a string to a float in Objective-C?

I am trying to multiply a couple of strings I am getting back from JSON:

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

NSLog(@"%@", subTotal);

This gives me: (null) in the console. I know that there is a valid string coming out of that array because I am already using it to display its value in a label.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只涨不跌 2024-09-15 03:04:53
your_float = [your_string floatValue];

编辑:

试试这个:

  NSLog(@"float value is: %f", your_float);
your_float = [your_string floatValue];

EDIT:

try this:

  NSLog(@"float value is: %f", your_float);
冰魂雪魄 2024-09-15 03:04:53

这样做的正确方法是

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

float value = [numberFormatter numberFromString:@"32.12"].floatValue;

The proper way of doing this is

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

float value = [numberFormatter numberFromString:@"32.12"].floatValue;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文