Alex Jenter
Alex Jenter

Reputation: 4432

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

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!

Upvotes: 0

Views: 611

Answers (2)

Alex Jenter
Alex Jenter

Reputation: 4432

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).

Upvotes: 0

Anonymous1847
Anonymous1847

Reputation: 2588

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

Upvotes: 0

Related Questions