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

Viewed 3001

I want to use the fmt library to format floating point numbers.

I try to format a floating point number with decimal separator ',' and tried this without success:

#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);
}

Output is 1.234567. I would like 1,234567

Update:

I browsed the source of the fmt library and think that the decimal separator is hard coded for floating point numbers and does not respect the current locale.

I just opened an issue in the fmt library

1 Answers

The fmt library made the decision that passing a locale as first argument is for overwriting the global locale for this call only. It is not applied to arguments with the f format specifier by design.

To format floating point number using locale settings the format specifier L has to be used, for example:

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

The L format specifier supports floating-point arguments as of revision 1d3e3d.

Related