User
User

Reputation: 65951

c++: How do I format a double to currency with dollar sign?

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

Upvotes: 3

Views: 19978

Answers (3)

Syntactic Fructose
Syntactic Fructose

Reputation: 20076

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

Upvotes: 1

tletnes
tletnes

Reputation: 1998

if(value < 0){
   ss << "-$" << std::fixed << -value; 
} else {
   ss << "$" << std::fixed << value; 
}

Upvotes: 5

ypnos
ypnos

Reputation: 52327

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.

Upvotes: 3

Related Questions