c++ - 如何实现以下C++输出格式?

标签 c++ formatting

我希望按照以下规则打印出 double :

1) No scietific notation
2) Maximum decimal point is 3
3) No trailing 0.

例如:

0.01        formated to  "0.01"
2.123411    formatted to "2.123"
2.11        formatted to "2.11"
2.1         formatted to "2.1"
0           formatted to "0"

通过使用. precision(3)和std::fixed,我只能实现规则1)和规则2),但不能实现规则3)

0.01        formated to  "0.010"
2.123411    formatted to "2.123"
2.11        formatted to "2.110"
2.1         formatted to "2.100"
0           formatted to "0"

代码示例如下:

#include <iostream>

int main() {
    std::cout.precision(3);
    std::cout << std::fixed << 0.01 << std::endl;
    std::cout << std::fixed << 2.123411 << std::endl;
    std::cout << std::fixed << 2.11 << std::endl;
    std::cout << std::fixed << 2.1 << std::endl;
    std::cout << std::fixed << 0 << std::endl;
    getchar();
}

有什么想法吗?

最佳答案

您无法使用 iostream 库的内置格式来执行此操作。

此外,您不需要对每个输出应用固定,因为它不会重置。

您可以编写自己的操纵器来执行此操作:

struct MyFormatter {
  int precision;
  double value;
  MyFormatter(int precision, double value) : precision(precision), value(value) {}
  friend std::ostream& operator<<(std::ostream& s, MyFormatter const& v) {
    std::stringstream ss;
    ss << std::set_precision(v.precision) << std::fixed << v.value;
    std::string str;
    ss.str().swap(str);
    str.resize(str.find_last_not_of("0") + 1);
    if (str[str.length() - 1] == '.') str.resize(str.length() - 1);
    s << str;
    return s;
  }
};

struct MyFormat {
  int precision;
  MyFormat(int precision) : precision(precision) {}
  MyFormatter operator()(double value) const {
    return MyFormatter(precision, value);
  }
};

int main() {
  MyFormat f(3);
  std::cout << f(0) << ' ' << f(0.1) << ' ' << f(0.12345) << '\n';
  return 0;
}

关于c++ - 如何实现以下C++输出格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2475642/

相关文章:

c++ - 从 printf 切换到 cout - 复杂格式说明符模式

全零的 C++ 结构初始化

cakephp - CakePHP 中的 TCPDF 奇怪问题

c# - 如何仅使用 InvariantCulture 渲染某些特定模型字段,而其余部分继续使用用户区域性?

c++ - 动态数组的运算符重载给出奇怪的错误

c++ - 将项目从qt4迁移到qt5时没有匹配的调用函数

c++ - 使用c++ ADO连接sql server 2017失败但返回null错误信息

intellij-idea - Intellij 中的链式方法和连续缩进

razor - 如何使用缩进和换行自动设置 Razor 输出格式?

objective-c - 以科学记数法显示 float