C ++打印,数字分组到小数点的*右边*

时间:2019-04-20 20:08:25

标签: c++ formatting iostream

我要打印双打,以便其小数部分的格式如下:

  • 0.123
  • 0.123 4
  • 0.123 45
  • 0.123 456
  • 0.123 456 7

我知道我可以继承std::numpunct并重载do_grouping()do_thousands_sep(),但是这些功能似乎只会影响到小数点。

#include <iostream>
#include <locale>

struct fmt : public std::numpunct<char> {
    string_type do_grouping() const { return "\3"; }
    char_type do_thousands_sep() const { return ' '; }
};

int main() {
    std::cout.imbue(std::locale(std::cout.getloc(), new fmt));
    std::cout.precision(10);
    std::cout << 12345.12345 << std::endl;
}

输出:

12 345.12345

是否有一种简单的方法可以自动在小数点的处添加空格?

编辑:

How to group decimal places as well?中,唯一的答案表明询问者编写了自己的函数。我的问题是是否有一种 easy 方式(就像另一个std::numpunct函数要重载)。我知道我可以编写自己的函数,但我想确认这样做是必要的。

0 个答案:

没有答案