c++: How do I format a double to currency with dollar sign?
c++, currency, dollar-sign, string, string-formatting
Solution
if(value < 0){
ss << "-$" << std::fixed << -value;
} else {
ss << "$" << std::fixed << value;
}
Problem
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".