如何将指数形式的十进制数字符串转换为Qt中的浮点数?

发布于 2024-09-19 06:25:39 字数 98 浏览 0 评论 0原文

我在文本文件中有一些以指数形式表示的十进制数字,例如:144.2e-3。我想将值存储为浮点数。在qt中,当我直接使用“number.toFloat()”方法时,它返回“0”。请帮忙。

I have some decimal numbers in a text file represented in exponential form Eg: 144.2e-3. I want to store the values in float. In qt it returns "0" when i directly use the "number.toFloat()" method. Please help.

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

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

发布评论

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

评论(3

梦一生花开无言 2024-09-26 06:25:39

toFloat() 应该可以工作。检查您的字符串是否仅包含数字。如果字符串还包含其他内容,例如 "144.2e-3 a",则 toFloat() 返回 0。请注意,字符串中的其他数字也会导致转换失败,例如QString("144.2e-3 100").toFloat() 将返回 0。

数字字符串中的额外空格并不重要,但其他字符却很重要。

toFloat() should work. Check that your string contains only the number. If the string contains something else too, for example "144.2e-3 a", then the toFloat() returns 0. Note that also other numbers in the string will cause the conversion to fail, for example QString("144.2e-3 100").toFloat() will return 0.

Additional whitespace in the number string doesn't matter, but other characters do.

笑梦风尘 2024-09-26 06:25:39
value = 3.91e+01;
double doubleValue;
stringstream valuestream(value);
valuestream >> doubleValue;

使用字符串流,您可以将指数数转换为我们需要的数据类型。

value = 3.91e+01;
double doubleValue;
stringstream valuestream(value);
valuestream >> doubleValue;

Using a stringstream you can convert exponential number to the datatype we require.

尐籹人 2024-09-26 06:25:39

使用QString::toDouble。

例子:

bool ok;
float f = static_cast< float>( QString( "1234.56e-02" ).toDouble( &ok));

Use QString::toDouble.

Example:

bool ok;
float f = static_cast< float>( QString( "1234.56e-02" ).toDouble( &ok));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文