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?
- 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...
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>
usingnamespace std;
usingnamespace 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!!!
}