C++ 将 double 转换为 QString
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5940846/
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
Convert a double to a QString
提问by Nagaraju
I am writing a program in QT. I want to convert a doubleinto a Qstringin C++.
我正在用 QT 编写程序。我想在 C++ 中将doublea转换为 a Qstring。
回答by Kristian
回答by Lars
Instead of QString::number()i would use QLocale::toString(), so i can get locale aware group seperatores like german "1.234.567,89".
而不是QString::number()我会使用QLocale::toString(),所以我可以获得像德语“1.234.567,89”这样的语言环境感知组分隔符。
回答by Tarek.Mh
You can use arg(), as follow:
您可以使用 arg(),如下所示:
double dbl = 0.25874601;
QString str = QString("%1").arg(dbl);
This overcomes the problem of: "Fixed precision" at the other functions like: setNum() and number(), which will generate random numbers to complete the defined precision
这克服了:在其他函数中的“固定精度”问题,例如:setNum() 和 number(),它们将生成随机数以完成定义的精度
回答by yano
Building on @Kristian's answer, I had a desire to display a fixed number of decimal places. That can be accomplished with other arguments in the QString::number(...)function. For instance, I wanted 3 decimal places:
基于@Kristian 的回答,我希望显示固定的小数位数。这可以通过函数中的其他参数来完成QString::number(...)。例如,我想要 3 个小数位:
double value = 34.0495834;
QString strValue = QString::number(value, 'f', 3);
// strValue == "34.050"
The 'f'specifies decimal format notation (more info here, you can also specify scientific notation) and the 3specifies the precision (number of decimal places). Probably already linked in other answers, but more info about the QString::numberfunction can be found here in the QStringdocumentation
在'f'指定十进制格式符号(详细信息在这里,你还可以指定科学计数法)和3指定的精度(小数位数)。可能已经在其他答案中链接,但QString::number可以在文档中找到有关该功能的更多信息QString
回答by jwd
Check out the documentation
查看文档
Quote:
引用:
QString provides many functions for converting numbers into strings and strings into numbers. See the arg()functions, the setNum()functions, the number()static functions, and the toInt(), toDouble(), and similar functions.
QString 提供了许多将数字转换为字符串和将字符串转换为数字的函数。参见ARG()函数中,setNum()函数,该 数()静态函数,和 toInt() ,toDouble(),和类似的功能。

