我有一个这样的部门:
number / 1000.0
有时它会给出类似 96.0000000001 的答案,有时除法会按预期工作。
我想将我的号码限制为最多两位小数,并且没有尾随零。
如果是 96.5500000001,它应该显示 96.55。
如果是 96.4000000001,它应该显示 96.4
这种方式可以格式化字符串吗?
我已经检查了文档,它提供了“f”参数来指定小数位数,但这样尾随零仍然存在。 这是我尝试过的:
QString::number(number / 1000.0, 'f', 2)
但这给了我 96.4000000001 --> 96.40 而不是 96.4
有什么解决办法吗?这种方式怎么格式化?
最佳答案
documentation很清楚你应该做什么:
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).
因此,请使用“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
构建并运行
qmake && make && ./main
输出
"96.4"
"96.55"
关于c++ - QString: 最多 2 位小数的数字,后面不带零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24882820/