C++ QString: 最多 2 个小数位的数字,不带尾随零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24882820/
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
QString:number with maximum 2 decimal places without trailing zero
提问by Nea?u Ovidiu Gabriel
I have a division like this:
我有一个这样的部门:
number / 1000.0
Sometimes it gives answers like 96.0000000001, sometimes the division works as expected.
有时它会给出 96.0000000001 之类的答案,有时该除法会按预期工作。
I want to limit my number to a maximum of two decimal places and without trailing zeros.
我想将我的数字限制为最多两位小数并且没有尾随零。
If it's 96.5500000001it should show 96.55.
如果是96.5500000001它应该显示96.55。
If it's 96.4000000001it should show 96.4
如果是96.4000000001它应该显示96.4
It is possible to format a string in this way?
可以以这种方式格式化字符串吗?
I've checked the documentation and it provides 'f' argument for specifying the number of the decimal places but this way the trailing zeros remain. This is what I have tried:
我已经检查了文档,它提供了用于指定小数位数的 'f' 参数,但这样尾随零仍然存在。这是我尝试过的:
QString::number(number / 1000.0, 'f', 2)
But this gives me for 96.4000000001--> 96.40instead of 96.4
但这给了我96.4000000001--> 96.40而不是96.4
Any solution? How can I format in this way?
有什么解决办法吗?我怎样才能以这种方式格式化?
回答by lpapp
The documentationis pretty clear about what you should do:
该文档非常清楚您应该做什么:
A precision is also specified with the argument format. For the 'e', 'E', and 'f' formats, the precision represents the number of digits after the decimal point. For the 'g' and 'G' formats, the precision represents the maximum number of significant digits (trailing zeroes are omitted).
参数格式也指定了精度。对于“e”、“E”和“f”格式,精度表示小数点后的位数。对于 'g' 和 'G' 格式,精度表示有效数字的最大数量(省略尾随零)。
Therefore, use either the 'g' or 'G' format.
因此,请使用“g”或“G”格式。
main.cpp
主程序
#include <QString>
#include <QDebug>
int main()
{
qDebug() << QString::number(96400.0000001 / 1000.0, 'g', 5);
qDebug() << QString::number(96550.0000001 / 1000.0, 'G', 5);
return 0;
}
main.pro
主程序
TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp
Build and Run
构建和运行
qmake && make && ./main
Output
输出
"96.4"
"96.55"
回答by jamess
This returns the formatted number always in fixed (not scientific) notation, and is reasonably efficient:
这将始终以固定(非科学)表示法返回格式化数字,并且相当有效:
QString variableFormat(qreal n) { // assumes max precision of 2
int i = rint(n * 100.0);
if (i % 100)
return QString::number(n, 'f', i % 10 ? 2 : 1);
else
return QString::number(i / 100);
}