Digit grouping

B

BigMan

Is it possible to specify digit grouping when writing to an output
stream (so that std::cout << 1234.56789; produces "1 234.567 89", for
example)? If so, how?
 
J

Jerry Coffin

BigMan said:
Is it possible to specify digit grouping when writing to an output
stream (so that std::cout << 1234.56789; produces "1 234.567 89", for
example)? If so, how?

This is all handled in the stream's locale, specifically the num_put
facet. The separators you've asked for don't match any of the usual
locales of which I'm aware, so you may have to create your own -- but
this is usually pretty simple (though I don't recall there being
anything about grouping digits after the decimal point).
 
J

Jerry Coffin

BigMan said:
Could you give me an example, please?

#include <locale>

template <class T>
struct formatter : std::numpunct<T> {
protected:
T do_decimal_point() const { return T('.'); }
T do_thousands_sep() const { return T(' '); }
std::basic_string<T> do_grouping() const {
return std::basic_string<T>("\3");
}
};

#ifdef TEST

#include <iostream>
#include <iomanip>

int main() {
// create a locale using our formatter.
std::locale l(std::locale::classic(), new formatter<char>);

// tell cout to use our new locale.
std::cout.imbue(l);

// print number out with enough precision to see groups
std::cout << std::setprecision(12) <<
std::setw(12) <<
1234567.89 <<
std::endl;
return 0;
}

#endif
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,291
Messages
2,571,455
Members
48,132
Latest member
KatlynC08

Latest Threads

Top