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

Recommended Answers

All 2 Replies

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

Perfect, thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.