是否有一个标准的格式化功能或操作符将向上舍入?(或者下来?)

0 c++ formatting ostringstream number-formatting

我使用ostringstream输出一个数字到2位小数,如下所示

std::ostringstream ostr;

ostr << std::fixed << std::setprecision(2);
ostr << cylinderLength;
Run Code Online (Sandbox Code Playgroud)

因此,如果cylinderLength = 0.594,则上述输出为预期的0.59.

是否有一个操作符或函数会在最后所需的小数位上向上或向下舍入?

在这种情况下,上面的例子将打印出0.60.

小智 6

尝试:

// Round towards +infinity (to 1 decimal place (use 100 for 2 decimal places)
ceil(double * 10) / 10


// Round towards -infinity (to 1 decimal place (use 100 for 2 decimal places)
floor(double * 10) / 10
Run Code Online (Sandbox Code Playgroud)