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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:03:26  来源:igfitidea点击:

Qt - Converting float to QString

c++qttype-conversion

提问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 floatobject into a QStringobject. I know there is the function QString::number()that can be used for other types like intand double, like so: int a = 1; QString b = QString::number(a);

这看起来应该很简单,但我正在浏览文档并没有看到任何东西。我只需要将表示为float对象的数字转换为QString对象。我知道有一个函数QString::number()可以用于其他类型,比如intand 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 floatto 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

floatwill auto-promote to doublewhen needed

floatdouble在需要时自动升级

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);