Formatting output of floating point numbers

M

Martin

Hi.

My question seems to be somewhat primitive, but I cannot find an
appropriate solution. Is it possible to control the number of digits
displayed in the exponent part of the scientific notation? I can use
'precision()' member function or 'setprecision' manipulator to control
the number of digits after the point:

cout.setf(ios_base::scientific, ios_base::floatfield);
cout.precision(8);
cout << 643.2963 << endl;

The result is 6.43296300e+002 with my stdlib. I want it to be printed
with 2 digits in exponent part, i.e. 02, not 002. How to achieve that?

Thanks in advance

Martin
 
V

Victor Bazarov

Martin said:
My question seems to be somewhat primitive, but I cannot find an
appropriate solution. Is it possible to control the number of digits
displayed in the exponent part of the scientific notation?

There is no easy standard way. Streams will output as many digits as
necessary and no more.

You can always write your own conversion routine which you can base on
stream conversion (say, to a string and then parsing that string).
I can use
'precision()' member function or 'setprecision' manipulator to control
the number of digits after the point:

cout.setf(ios_base::scientific, ios_base::floatfield);
cout.precision(8);
cout << 643.2963 << endl;

The result is 6.43296300e+002 with my stdlib. I want it to be printed
with 2 digits in exponent part, i.e. 02, not 002. How to achieve that?

By extracting the part after 'e' and shortening it.

V
 

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,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top