在将 float 转换为字符串时,是否有一种简单的方法可以在 C++ 中设置小数点后的非固定精度?
std::setprecision( 2 ) 所做的是:
1.00000 -> 1
1.23456 -> 1.2
12.3456 -> 12
12.3000 -> 12.3
std::fixed 添加的内容是:
1.00000 -> 1.00
1.23456 -> 1.20
12.3456 -> 12.34
12.3000 -> 12.30
我想做的是:
1.00000 -> 1
1.23456 -> 1.23
12.3456 -> 12.34
12.3000 -> 12.3
最佳答案
以下舍入到两位小数,然后使用默认精度:
#include <iostream>
#include <iomanip>
#include <cmath>
int main()
{
double vals[]{1.00000, 1.23456, 12.3456, 12.3000};
for(auto i : vals) {
i = std::round(i * 100) / 100;
std::cout << i << '\n';
}
}
产生:
1
1.23
12.35
12.3
关于c++ float to string non-fixed precision after decimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46327330/