precision formatting for iostream

Suppose I have 10 columns and a million rows in a matrix and I want to implement operator<<. Each of the 10 columns has a different, but known precision. I want to output this matrix into a CSV file, one row at a time.

Does this mean I have to call setprecision() 10 million times or is there a better way about this?

If not, I am tempted to go back to fprintf()...

Last edited on
You could re-order it so it goes:

COLUMN 1 COLUMN 1 ...
COLUMN 2 COLUMN 2 ...

Otherwise, you could make a small inline function/macro that takes 10 numbers and prints them out with the correct precisions. i.e.:

1
2
//for 2 numbers
#define print_stuff(a,b) std::cout<<setprecision(2)<<a<<setprecision(3)<<b<<std::endl; 
Hi firedraco,

Thx for responding so quickly.

- I can't invert the matrix - it has to go into the CSV file as-is.
- #define won't work for me as my matrix class is a template (has an indefinite number of columns)

I am tempted to use boost::format(), if I find no other options.

BTW, one thing I find surprising is that there is no special format which keeps track of precision.
For example,

If I have:

1
2
double x = 123.45;
double y = 123.4567;


I would like the corresponding strings "123.45" and "123.4567" to print out to the same precision as my actual doubles (IMHO, that should be the default behavior for double to string conversion)...

I wonder if there is a way to do that. If there is, I wouldn't have to worry about setprecision() at all, because other parts of my code keep track and ensure that there is proper precision in double calculations...

Last edited on
It looks like boost's lexical_cast fits the bill, but I spoke too soon: there are decimal-representation issues, so it almost seems like I need a Currency or Money class.

Try:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>

using namespace std;
using namespace boost;

void foo( void )
{
  double x = 123.45;
  double y = 123.4567;
  double z = 99751.24;

  cerr << lexical_cast<string>( x ) << endl;  // 123.45 yeah!
  cerr << lexical_cast<string>( y ) << endl;  // 123.4567 yeah, yeah!
  cerr << lexical_cast<string>( z ) << endl;  // 99751.24000000001 OH, NOOOOOO!!!
}

Last edited on
Ah, that is a problem with how the computer represents doubles/floats...read this for info on it:
http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.16
Topic archived. No new replies allowed.