Search code examples
c++stringstring-formattingcurrencydollar-sign

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


Solution

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