四舍五入到小数点后3位
当前,我可以使用以下命令将 double
舍入为输出流:
Currently, I can round a double
to an output stream using:
output.setf(std::ios::fixed,std::ios::floatfield);
output.precision(3);
但是我得到了 double
和在将其插入向量之前,需要进行转换。例如,如果出现数字 -0.00078
,则它等于 0.000
,而我不需要保存它。另一方面, 1.0009
将变为 1.001
(与precision函数相同)。
But I'm given a double
and I need to make the conversion before I insert it to a vector. So for instance, if the number -0.00078
appears then it equals to 0.000
and I won't need to save it. On the other hand, 1.0009
will become 1.001
(same as the precision function handles it).
如何在C ++中转换成双精度?
How can I convert doubles like that in C++?
一个常见的技巧是用数学来做:
A common trick is to do it with maths:
value = round( value * 1000.0 ) / 1000.0;
其中整轮
将处理负值和正值正确...这样的东西(未经测试):
Where round
will handle negative and positive values correctly... Something like this (untested):
inline double round( double val )
{
if( val < 0 ) return ceil(val - 0.5);
return floor(val + 0.5);
}
由于输出,您仍需要将小数位设置为3浮点精度问题。
You'll still want to set the decimal places to 3 during output, due to floating point precision problems.