3

I have a function that takes a double and returns it as string with thousand separators. You can see it here: c++: Format number with commas?

#include <iomanip>
#include <locale>

template<class T>
std::string FormatWithCommas(T value)
{
    std::stringstream ss;
    ss.imbue(std::locale(""));
    ss << std::fixed << value;
    return ss.str();
}

Now I want to be able to format it as currency with a dollar sign. Specifically I want to get a string such as "$20,500" if given a double of 20500.

Prepending a dollar sign doesn't work in the case of negative numbers because I need "-$5,000" not "$-5,000".

Community
  • 1
  • 1
User
  • 62,498
  • 72
  • 186
  • 247
  • 2
    Working with currency, you might consider [`std::put_money`](http://en.cppreference.com/w/cpp/io/manip/put_money). – chris Dec 04 '12 at 23:52

3 Answers3

5
if(value < 0){
   ss << "-$" << std::fixed << -value; 
} else {
   ss << "$" << std::fixed << value; 
}
tletnes
  • 1,958
  • 10
  • 30
3

I think the only thing you can do there is

ss << (value < 0 ? "-" : "") << "$" << std::fixed << std::abs(value);

You need a specific locale to print with the thousand separators.

ypnos
  • 50,202
  • 14
  • 95
  • 141
1

Here is an example program i used to learn about formatting currency pulled from here. Try and pick this program apart and see what you can use.

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

void showCurrency(double dv, int width = 14)
{
    const string radix = ".";
    const string thousands = ",";
    const string unit = "$";
    unsigned long v = (unsigned long) ((dv * 100.0) + .5);
    string fmt,digit;
    int i = -2;
    do {
        if(i == 0) {
            fmt = radix + fmt;
        }
        if((i > 0) && (!(i % 3))) {
            fmt = thousands + fmt;
        }
        digit = (v % 10) + '0';
        fmt = digit + fmt;
        v /= 10;
        i++;
    }
    while((v) || (i < 1));
    cout << unit << setw(width) << fmt.c_str() << endl;
}

int main()
{
    double x = 12345678.90;
    while(x > .001) {
        showCurrency(x);
        x /= 10.0;
    }
    return 0;
}
Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177