更新时间:2023-02-21 16:08:48
是您实际上是尝试舍入数字,还是只是更改其显示精度?
Are you actually trying to round the number, or just change its displayed precision?
对于前者(将多余的数字截断):
For the former (truncating the extra digits):
double scale = 0.01; // i.e. round to nearest one-hundreth
value = (int)(value / scale) * scale;
或(根据jheriko的回答,四舍五入)
or (rounding up/down as appropriate, per jheriko's answer)
double scale = 0.01; // i.e. round to nearest one-hundreth
value = floor(value / scale + 0.5) * scale;
对于后者:
cout << setprecision(2) << value;
其中 setprecision()
的参数为小数点后显示的最大位数。
where the parameter to setprecision()
is the maximum number of digits to show after the decimal point.