The format controls do not insert either the thousands separator or the currency symbol. To do this you need to use locales and the
money_put
facet. However this is not pretty.
The following code outputs a value in US dollars:
int main()
{
std::locale loc("US")
const std::money_put<char>& output =
std::use_facet<std::money_put<char> >(loc)
std::ostreambuf_iterator<char, std::char_traits<char> > iterator(std::cout)
std::cout.imbue(loc)
std::cout.setf(std::ios_base::showbase)
std::cout << "Value is: "
output.put(iterator, false, std::cout, ' ', 12300000.0)
std::cout << std::endl
return 0
}
If the second parameter to
money_put.put
is
false
then the currency symbol is output (e.g. $123,000.00), if set to
true
then the international monetary sign is used (e.g. USD123,000,00).
The value is interpreted as a value in cents (in general it is the smallest unit of the locale's currency).
However mixing normal values and currency values in the output stream is awkward, imbuing
std::cout
with a locale affects all subsequent output (which may or may not be what you want). The way round this is to using
money_put
on a string, and wrap this in a class to make everything easier:
#include <iostream>
#include <iterator>
#include <locale>
#include <string>
#include <sstream>
class MoneyOutputter
{
public:
MoneyOutputter(const char* const locale_name = "US") :
loc(locale_name),
output(std::use_facet<std::money_put<char> >(loc)),
iterator(os)
{
os.imbue(loc);
os.setf(std::ios_base::showbase);
}
std::string as_string(double value)
{
os.str("");
output.put(iterator, false, os, ' ', value * 100.0);
return os.str();
}
private:
std::locale loc;
const std::money_put<char>& output;
std::ostringstream os;
std::ostreambuf_iterator<char, std::char_traits<char> > iterator;
};
int main()
{
MoneyOutputter outputter;
double value1 = 235460.0;
double value2 = 123000.0;
double value3 = 4500.0;
double value4 = 545.0;
std::cout << "Jones " << value1 << " " << outputter.as_string(value2) << " "
<< outputter.as_string(value3) << " " << outputter.as_string(value4)
<< std::endl;
return 0;
}