如何使用 fmt 库格式化带十进制逗号的浮点数?

How to format floating point numbers with decimal comma using the fmt library?

我想使用 fmt 库格式化浮点数。

我尝试用小数分隔符“,”格式化浮点数,但没有成功:

#include <iostream>
#include <fmt/format.h>
#include <fmt/locale.h>

struct numpunct : std::numpunct<char> {
  protected:    
    char do_decimal_point() const override
    {
        return ',';
    }
};

int main(void) {
    std::locale loc;
    std::locale l(loc, new numpunct());
    std::cout << fmt::format(l, "{0:f}", 1.234567);
}

输出为 1.234567。我想要1,234567

更新:

我浏览了 fmt 库的源代码,认为浮点数的小数分隔符是 hard coded,不符合当前语言环境。

我刚开了一个issue in the fmt library

fmt 库决定将区域设置作为第一个参数传递,仅用于覆盖此调用的全局区域设置。根据设计,它不适用于具有 f 格式说明符的参数。

要使用区域设置格式化浮点数,必须使用格式说明符 L,例如:

std::locale loc(std::locale(), new numpunct());
std::cout << fmt::format(loc, "{0:L}", 1.234567);

从修订版 1d3e3d 开始,L 格式说明符支持 floating-point 个参数。