c++ - QString: 最多 2 位小数的数字,后面不带零

标签 c++ qt precision qstring qtcore

我有一个这样的部门:

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/

相关文章:

c++ - QDialog 基于 QLabel 内容扩展

c++ - 逻辑或表达式 c++

javascript - 如何在 QWebEngineView 中将值从 QML 传递给 JavaScript

windows - 使 qt 分布整洁。删除部分dll?

comparison - 测试 float 是否等于 0.0 是否安全?

algorithm - 通过日志处理小概率

c++ - 初始化指针或引用成员变量以指向另一个成员

c++ - 错误 : expected primary-expression before 'char'

qt - 将qt移植到另一个操作系统就这么简单吗?

r - 计算大 d 和 a 的和 ((v/u) * (d^a)) ^ (1/a)