1

如何使用 stringstream 打印双数点后的最大小数位数(无尾随零且无舍入)?例如,如果我只想打印最多 5 个小数位:

1 -> 1
1.23 -> 1.23
1.234 -> 1.234
1.2345 -> 1.2345
1.23456 -> 1.23456
1.234567 -> 1.23456
1.2345678 -> 1.23456
1230.2345678 -> 1230.23456 <- Demonstrating that I am not talking about significant digits of the whole number either

等等

在我看到的所有工具(setw、setprecision、fixed 等)中,我似乎无法弄清楚这一点。谢谢!

4

2 回答 2

1

你绝对想用stringstream选项来做这件事吗?

您可以编写这样的round函数:

double round(double n, int digits) {
    double mult = pow(10, digits);
    return floor(n*mult)/mult;
}

然后只需打印round(1.2345678, 5).

于 2012-11-01T22:55:56.873 回答
0

没有内置的方法可以做到这一点(据我所知)。然而,像下面这样的 hack 是可能的:

void print_with_places(double num, unsigned places) {
   for (double i = 1; i < num; i*=10) { //have to use a double here because of precision...
      ++places;
   }
   std::cout << std::setprecision(places) << num;
}

它不是最漂亮的,但就是这样或将其打印到字符串然后操作字符串。

于 2012-11-01T22:57:07.620 回答