Write all numbers with 3 decimals?

D

desktop

I have a program that writes something like this:

0 0 -1 0
-0.6 0.8 0 0
0.8 0 0 0
0 0 0 1


I write that with this statement:

std::cout << m[j] << " ";

in a loop. Is there some way to print all numbers with 3 decimals
including the potential minus, so I get something like this:

0.00 -1.0
-0.6 0.80
0.80 0.00

etc
 
V

Victor Bazarov

desktop said:
I have a program that writes something like this:

0 0 -1 0
-0.6 0.8 0 0
0.8 0 0 0
0 0 0 1


I write that with this statement:

std::cout << m[j] << " ";

in a loop. Is there some way to print all numbers with 3 decimals
including the potential minus, so I get something like this:

0.00 -1.0
-0.6 0.80
0.80 0.00


See 'std::fixed', 'std::setw', 'std::setprecision' and other I/O
stream manipulators. The header is <iomanip>.

V
 
J

James Kanze

I have a program that writes something like this:
0 0 -1 0
-0.6 0.8 0 0
0.8 0 0 0
0 0 0 1
I write that with this statement:
std::cout << m[j] << " ";

in a loop. Is there some way to print all numbers with 3 decimals
including the potential minus, so I get something like this:
0.00 -1.0
-0.6 0.80
0.80 0.00

Not directly. First of all, there is absolutely no way to get
the minus sign to be counted as a digit. And even if all of the
values were positive, I don't think you could do it. By
formatting each value into a stringstream, then formatting the
resulting string, it can be done, however:

// before outputting the table...
std::cout.setf( std::ios::left, std::ios::adjustfield ) ;
std::cout.fill( '0' ) ;
// ...
// for each element...
std::eek:stringstream tmp ;
tmp.setf( std::ios::showpoint ) ;
tmp.precision( 1 ) ;
tmp << table[j] ;
std::cout << ' ' << std::setw( 4 ) << tmp.str() ;

In practice, of course, you'll definitly want to save the
stream's formatting state, and restore it afterwards; I doubt
that your collegues would appreciate the fact that the fill
character has suddenly become '0' after your function has been
called.

And are you sure that this is what you want. It's a very
unusual format, and typically, something which aligns the
decimals would be more appropriate. If you're doing any numeric
work at all, you doubtlessly already have a custom manipulator
for doing this, so you could just write:
std::cout << ' ' << FFmt( 5, 2 ) << table[ i ][ j ] ;
or something like that. Correctly written, FFmt also eliminates
the need for saving and restoring the format flags, so your
format modifications don't affect others.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top