How to specify a custom decimal separator for numbers in Boost.Locale?

530 Views Asked by At

I've read the Boost.Locale docs several times through, but still can't find the answer to this seemingly easy problem: I need to output using a specific locale (e.g. ru_RU), but with a customized decimal separator (e.g. dot instead of comma). Is this possible?

For dates, there's the "ftime" manipulator that allows to specify a custom datetime format string. But is there anything like that for numbers?

Thanks!

2

There are 2 best solutions below

1
Anonymous1847 On BEST ANSWER

You can use the C++ <locale> library.

std::string russian_number_string(int n) {
    std::stringstream ss;
    ss.imbue(std::locale("ru_RU"));
    ss << n;
    return ss.str();
}
0
Alex Jenter On

For the sake of completeness, I'll post how I've solved the problem. Say we have a locale object and need to use a custom decimal point character sep:

template <class charT>
class DecimalPointFacet : public std::numpunct<charT> {
    charT _sep;

public:
    explicit DecimalPointFacet(charT sep): _sep(sep) {}

protected:
    [[nodiscard]] charT do_decimal_point() const override
    {
        return _sep;
    }

    [[nodiscard]] typename std::numpunct<charT>::string_type do_grouping() const override
    {
        return "\0";
    }
};

// ...

std::locale locale = obtainLocale();
const char sep = obtainDecimalSeparator();
locale = std::locale(locale, new DecimalPointFacet<char>(sep);
std::cout.imbue(locale);
std::cout << someNumber;

Note also that the DecimalPointFacet turns off grouping of digits which was also handy for me(if you don't need that, remove the do_grouping override).