【发布时间】:2021-09-13 15:15:10
【问题描述】:
我的浮点数范围从 0.001 到 999.999 问题:如何像这样格式化所有范围数字:
0.001 变成 000.001
0.002 变成 000.002
0.2 变成 000.200
1.001 变成 001.001
9.090 变成 009.090
99.100 变为 099.100
谢谢
【问题讨论】:
标签: c++
我的浮点数范围从 0.001 到 999.999 问题:如何像这样格式化所有范围数字:
0.001 变成 000.001
0.002 变成 000.002
0.2 变成 000.200
1.001 变成 001.001
9.090 变成 009.090
99.100 变为 099.100
谢谢
【问题讨论】:
标签: c++
请检查stream manipulators的文档。
有几个工具可以让你做到这一点:
while (std::cin >> x) {
std::cout
<< std::setfill('0') << std::setw(7)
<< std::fixed << std::setprecision(3)
<< x << '\n';
}
std::fixed 强制使用固定格式(小数分隔符在同一位置)std::setprecision(3) 定义小数点分隔符后应有多少位。std::setw(7) - 定义应占用的最小空间数std::setfill('0') 定义了应该使用什么来填充 std::setw(7) 引入的额外空间。https://godbolt.org/z/zf6q8n97r
C++20 引入了与来自 C:format 的 printf 的良好类型安全且干净的等价物,但是没有编译器已经支持它。
【讨论】:
使用 iomanip 的 std 流格式化程序。 停止使用 printf :Why not use printf() in C++
#include <iostream>
#include <iomanip>
#include <vector>
int main()
{
std::vector<double> values{ 0.001, 0.002, 0.2, 1.001, 9.090, 99.100 };
for (const auto value : values)
{
std::cout << std::fixed;
std::cout << std::setprecision(3);
std::cout << std::setfill('0') << std::setw(7);
std::cout << value << std::endl;
}
return 0;
}
【讨论】:
#include <cstdio>
int main(void)
{
float f = 99.01f;
std::printf("%07.03f", f);
}
07 指定如果数字占用的空间少于 7 个字符,它将用前导 0s 填充,而 03 指定如果小数点后的数字占用的空间少于 3 个字符然后它会被尾随的0s 填充。
从 C++20 开始,您可以在 std::format 中使用类似的格式:
std::cout << std::format("{:07.03f}", f);
【讨论】: