【问题标题】:Is there a standard formatting function or operator that will round up? (or down?)是否有标准的格式化函数或运算符可以四舍五入? (或下降?)
【发布时间】:2013-01-12 06:31:28
【问题描述】:

我正在使用 ostringstream 将数字输出到小数点后 2 位,如下所示

std::ostringstream ostr;

ostr << std::fixed << std::setprecision(2);
ostr << cylinderLength;

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

是否有一个运算符或函数可以向上或向下舍入到最后一个所需的小数位?

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

【问题讨论】:

  • 你需要ceil()
  • @AlokSave 如果在我的测试中使用 ceil,它将变为 1
  • 所以您想在特定的小数位数处向上或向下舍入?
  • 是的,我想到了ceil,但它被定义为“返回不小于x的最小整数值”。我希望在最后一个所需的小数位上应用四舍五入。
  • @AndrewS.:检查 Loki 对答案的编辑。

标签: c++ formatting number-formatting ostringstream


【解决方案1】:

试试:

// 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

【讨论】:

  • 是的,这显然有效 - 谢谢。但是没有函数或方法可以直接做到这一点吗?我想尝试不同的舍入精度,所以这有点笨拙。
  • @AndrewS。您可以编写一个包装器来执行此操作。
猜你喜欢
  • 2010-11-13
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 2013-09-15
  • 2022-01-09
  • 1970-01-01
相关资源
最近更新 更多