如何对小数位进行分组

How to group decimal places as well?

本文关键字:小数      更新时间:2023-10-16

我想得到x = 1,234,567,890.098,765,432,1 .

#include <iostream>
#include <string>
#include <iomanip>
#include <locale>
using namespace std;

struct separated : numpunct<char>
{
    string do_grouping() const { return "3"; }
};

int main()
{
    const double x = 1234567890.0987654321;
    locale our_local(cout.getloc(), new separated);
    cout.imbue(our_local);
    cout << fixed;
    cout << setprecision(10);
    cout << "x = " << x << endl;
    return 0;
}

输出:x = 1,234,567,890.0987654321

预期输出:x = 1,234,567,890.098,765,432,1

如果你能使它更通用,那就更好了,如下所示,

  • x = 1'234'567'890.098'765'432'1
  • x = 1_234_567_890.098_765_432_1

小数点为点 (US-EN(。

问题

如何对小数位进行分组?

编辑

x 属于 double 类型,而不是文本字符串。

这是一个算法:

创建一个函数,该函数将要转换的数字作为其参数。 将该数字转换为字符串。 扫描字符串中的小数点(同时注意非数字结果(如无穷大或不确定(的可能性(。 如果找到,请处理字符串的其余部分,每隔三个数字插入分隔符,到达字符串末尾或非数字(例如,指定指数的E(时停止。 返回此字符串。

作为

附加练习,创建此函数的一个版本,该版本可以作为操纵器传递给cout