【问题标题】:float number leading and trailing zeros format浮点数前导和尾随零格式
【发布时间】:2021-09-13 15:15:10
【问题描述】:

我的浮点数范围从 0.001 到 999.999 问题:如何像这样格式化所有范围数字:

0.001 变成 000.001

0.002 变成 000.002

0.2 变成 000.200

1.001 变成 001.001

9.090 变成 009.090

99.100 变为 099.100

谢谢

【问题讨论】:

标签: c++


【解决方案1】:

请检查stream manipulators的文档。

有几个工具可以让你做到这一点:

    while (std::cin >> x) {
        std::cout 
            << std::setfill('0') << std::setw(7) 
            << std::fixed << std::setprecision(3)
            << x << '\n';
    }
  • std::fixed 强制使用固定格式(小数分隔符在同一位置)
  • std::setprecision(3) 定义小数点分隔符后应有多少位。
  • std::setw(7) - 定义应占用的最小空间数
  • std::setfill('0') 定义了应该使用什么来填充 std::setw(7) 引入的额外空间。

https://godbolt.org/z/zf6q8n97r

补充说明:

C++20 引入了与来自 C:formatprintf 的良好类型安全且干净的等价物,但是没有编译器已经支持它。

【讨论】:

    【解决方案2】:

    使用 iomanip 的 std 流格式化程序。 停止使用 printf :Why not use printf() in C++

    #include <iostream>
    #include <iomanip>
    #include <vector>
    
    
    int main()
    {
        std::vector<double> values{ 0.001, 0.002, 0.2, 1.001, 9.090, 99.100 };
    
        for (const auto value : values)
        {
            std::cout << std::fixed;
            std::cout << std::setprecision(3);
            std::cout << std::setfill('0') << std::setw(7);
            std::cout << value << std::endl;
        }
    
        return 0;
    }
    

    【讨论】:

    • 谢谢大家,非常感谢和尊重
    【解决方案3】:

    std::printf:

    #include <cstdio>
    
    int main(void)
    {
        float f = 99.01f;
        std::printf("%07.03f", f);
    }
    

    07 指定如果数字占用的空间少于 7 个字符,它将用前导 0s 填充,而 03 指定如果小数点后的数字占用的空间少于 3 个字符然后它会被尾随的0s 填充。

    从 C++20 开始,您可以在 std::format 中使用类似的格式:

    std::cout << std::format("{:07.03f}", f);
    

    【讨论】:

      猜你喜欢
      • 2011-01-27
      • 1970-01-01
      • 2022-09-29
      • 2023-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多