How to convert string to double dollars using C++ string stream, a STL container, and locale

(Last Updated On: May 18, 2010)

How to convert string to double dollars using C++ string stream, STL containers, and locale


using namespace std;

void to_dollar(int a);

int my_number_format(int num)
int idx;
char buffer[64];

idx = sizeof(buffer)-1;
buffer[idx–] = 0; // end zero

int count = 0;
while (num > 0) {
if (0 == idx)
return -1;
if (count > 2) {
buffer[idx–] = ‘,’;
if (0 == idx)
return -1;
count = 0;
buffer[idx–] = ‘0’+(num % 10);
num /= 10;

buffer[idx] = ‘$’; // currency sign
return printf(“%s\n”, &buffer[idx]);

int main()
int userInput;

cout << "Please enter an integer-:> ” << endl; cin >> userInput;
int result;
return (0);

void to_dollar(int a)
stringstream inString;
string strTemp;
long double intTemp;

inString << a; // convert integer to string for easier handling inString.str(inString.str()+"00"); // concatenate two zeos to denote currency fractional digits inString >> intTemp; // convert back to integer

locale loc(“english_USA”); // set the locale

cout.setf(cout.flags() | ios::showbase); // turn on currency sign printing
const money_put& m_put = use_facet >(loc); // get the money_put facet
m_put.put(cout, false, cout, ‘ ‘, intTemp); // show me the money. Note to use fractionally adjusted value.
cout << endl; }

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Subscribe For Latest Updates

Sign up to best of business news, informed analysis and opinions on what matters to you.
Invalid email address
We promise not to spam you. You can unsubscribe at any time.
Scroll to Top