0

when using #include <iomanip> ; what is the syntax for formating numerical values for currency - example 123456, format to $123,456. Using the cout << command.

2
Contributors
2
Replies
3
Views
12 Years
Discussion Span
Last Post by dallin
0

C++ doesn't have native support for working with monetary values. You need to either find a library that does what you want, or roll your own:

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

using namespace std;

string currency ( double value )
{
  ostringstream sout;

  sout<< fixed << setprecision ( 2 ) << value;
  
  string s = sout.str();
  int n = 0;

  for ( string::size_type i = s.length() - 4; i > 0; i-- ) {
    if ( ++n == 3 ) {
      s.insert ( s.begin() + i, ',' );
      n = 0;
    }
  }

  return '$' + s;
}

int main()
{
  cout<< currency ( 1234567.890 ) <<endl;
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.