Francesco S. Carta wrote:
> > Hi all
> > is there a function for converting a number such as 1234567.89 into a
> > string presentation as "1,234,567.89" for printing? Thanks for any
> > hints!
> > kwwang
>
> Nothing straight out of the standard C++ box.
This is one of those perennial FAQs that everyone needs and nobody
covers. The locale/facets system in iostreams is apparently a kit for
you to assemble.
The ultimate problem appears to be some undiscovered culture somewhere
might separate hundreds, or ten-thousands, so a locale cannot simply
assume thousands and then ask what delimiter goes there!
http://www.velocityreviews.com/forum...le-output.html
#include <sstream>
#include <iostream>
#include <locale>
#include <string>
// custom numeric punctuation facet
struct Punct: std::numpunct<char>
{
char do_thousands_sep () const
{
return ',';
}
std::string do_grouping () const
{
return "\3";
}
};
std::string toStr(int x,std::locale const& l)
{
std::stringstream stream;
stream.imbue(l);
stream << x;
return stream.str();
}
int main()
{
// construct a custom punctuation facet
std::numpunct<char>* punct = new Punct;
// construct a locale containing the custom facet
const std::locale locale(std::cout.getloc(),punct);
std::cout.imbue(locale);
std::cout << "Val: " << 1234556 << std::endl;
std::cout << "From String: " << toStr(123456789,locale) <<
std::endl;
}
That thread then gets the James Kanze treatment, so read his prose to
learn what horrors I just pasted in, untested!
--
Phlip