c++ - cout 浮动,没有尾随零,并且后面只有 3 位数字
问题描述
我正在尝试打印一个float
变量,我希望它只有 3 位数字。但是,如果它们为零,则它们最终不会打印。
例如
1.230 -> should be out like this 1.23
1.456432 -> 1.456
1.4000006 -> 1.4
目前我正在使用
cout<<fixed<<setprecision(3) <<res2<<endl;
它仍然显示更多的零,例如 0.010 但它应该是 0.01
解决方案
一种方法是使用手动将其解析为字符串stringstream
并删除尾随零。与string::find_last_not_of。编辑:正如@Eljay 指出的那样,find_last_not_of
不适用于1010
or之类的情况120
。相反,以下代码只是不断删除最后一个0
或.
如果存在浮点。
#include "iostream"
#include "iomanip"
#include "vector"
using std::cout;
using std::string;
using std::setprecision;
using std::fixed;
using std::stringstream;
using std::vector;
string removeTrailingZeros(float number) {
stringstream stream;
stream << fixed << setprecision(3) << number;
string floatStr = stream.str();
while (floatStr.find('.') != string::npos && floatStr.back() == '0' || floatStr.back() == '.')
floatStr.pop_back();
return floatStr;
}
int main() {
vector<float> numbers = {
1010,
120,
1.50005,
0.004,
1.9994,
1.9996,
2.4321,
0,
-1.5,
0.69,
0.1,
1.007
};
for (auto n : numbers) {
cout << fixed << setprecision(3) << n << ": " << removeTrailingZeros(n) << '\n';
}
return 0;
}
输出:
1010.000: 1010
120.000: 120
1.500: 1.5
0.004: 0.004
1.999: 1.999
2.000: 2
2.432: 2.432
0.000: 0
-1.500: -1.5
0.690: 0.69
0.100: 0.1
1.007: 1.007
推荐阅读
- c# - 如何订购角色层次结构以访问 MVC5 中的授权页面?
- mysql - 如何使此 sql 查询与 mysql 的旧版本(如 v.5.5 及更高版本)兼容?
- java - 如何使用 JPA Criteria Builder 按长度(列名)排序
- javascript - angular 8 routerLink 在 ios 设备浏览器中无法正常工作
- google-apps-script - Google-sheet:从导入的范围中选择相关单元格
- mysql - 错误 ERROR 2013 (HY000):在 Lightsail 上设置组复制的查询期间丢失与 MySQL 服务器的连接
- react-native - Redux TypeError:传播不可迭代实例的无效尝试。为了可迭代,非数组对象必须有一个 [Symbol.iterator]() 方法
- html - 我正在尝试使用 pdfkit 将 HTML 模板转换为 PDF,但模板中的数据未加载到 pdf 中
- python - Python MIMEText 在消息中添加(随机?)不需要的新行
- html - Flex-wrap - 无效的属性值