C++ Qt - 将浮点数转换为 QString
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22383820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Qt - Converting float to QString
提问by thnkwthprtls
This seems like it should be very simple, but I'm going through the docs and not seeing anything. I just need to convert a number that is represented as a float
object into a QString
object. I know there is the function QString::number()
that can be used for other types like int
and double
, like so:
int a = 1;
QString b = QString::number(a);
这看起来应该很简单,但我正在浏览文档并没有看到任何东西。我只需要将表示为float
对象的数字转换为QString
对象。我知道有一个函数QString::number()
可以用于其他类型,比如int
and double
,如下所示:
int a = 1;
QString b = QString::number(a);
...however this doesn't seem to work for float
. Perhaps there is some way where it is converted first from float
to another type, and then from that type to QString
? If anyone has any ideas I'd appreciate it. Thanks!
...但是这似乎不适用于float
. 也许有某种方法可以先将它从转换float
为另一种类型,然后再从该类型转换为QString
? 如果有人有任何想法,我将不胜感激。谢谢!
回答by ratchet freak
float
will auto-promote to double
when needed
float
将double
在需要时自动升级
float pi = 3.14;
QString b = QString::number(pi);
should work
应该管用
otherwise you can use setNum:
否则你可以使用 setNum:
float pi = 3.14;
QString b;
b.setNum(pi);