tags:

views:

185

answers:

1

The following code displays floating-point numbers in scientific notation:

float foo = 1.0;
::cout::setf(::std::ios::scientific);
::std::cout << foo;

It produces this output:

1.000000e-000

What I would like to do is display floating-point numbers in a specific notation which resembles the scientific notation but with a mantissa set to zero. With the same floating-point number as above, it would produce:

0.100000e+001

In C, I believe it would be written this way:

printf("%.6E", foo);

Update: Well, actually I don't know how to do it in C as well. Update2: The example using iostream formatting was incorrect. I modified it according to Michael Burr's comment.

+2  A: 

If you want to do this with ostreams, I think you'll need to use "facets". This little-known part of C++ lets you control formatting pretty much however you like.

Here's a description of num_put, which is what formats the numbers in the way you don't like: http://www.cplusplus.com/reference/std/locale/num%5Fput/

You'll need to "imbue" your ostream (literally ostr.imbue()) with a locale containing the facet you'll create to format numbers the way you want.

I suggest starting by writing a function to convert a number to a string using the formatting you want. Once you have that, if you wish to go whole hog and do the locale & facet stuff, you can (or maybe you'll decide it's too complex, which is what most people end up doing).

John Zwinck