7

This code:

#include <iostream>
int main( int, char **argv )
{
std::cout << 1.23e45 << std::endl;
}

prints

1.23e+045

when compiled with MS Visual Studio 2003, and

1.23e+45

on my Linux machine.

How can I specify the width of the exponent field (and why is there a difference in the first place)?

3 Answers 3

1

I don't think this is possible with standard manipulators. (if it is, I'd love to be corrected and learn how)

Your only remaining option is creating a streambuf yourself, and intercepting all exponent numbers that go to the stream, reformat them by hand, and pass them on to the underlying stream.

Seems a lot of work, and while not rocket science, no trivial task either.

On the 'why' question: I know linux defines the exponent as minimum two digits, I suppose Windows specifies it as minimum three?

// on linux
std::cout << std::scientific << 1.23e4 << std::endl

Also adds a leading zero:

1.230000e+04
1
  • You can also calculate mantissa and exponent by hand as described here, and then use sprintf or whatever.
    – Paul Lynn
    Mar 20, 2021 at 22:36
1

As a follow-up of @Pieter's answer, I've been looking inside the operator<< (ostream&, double). Indeed, there is no field to specify the significance or width of the exponent. On windows, the operator<< forwards to sprintf, which has no exponent-size either.

In it's turn, the sprintf function (on Windows) calls into _cfltcvt_l, a function we have no source code for, but whose signature doesn't provide for an exponent-precision.

I know nothing of the implementation on Linux.

-1

Look into the iomanip header. It has a lot of width-precision etc... functionality.

3
  • Which one do I need? the width is the full width, the precision is the number of digits of the mantissa. Nov 6, 2008 at 13:26
  • as far as I know it's not possible with default iomanip attributes, as you said, both precision and width do something else...
    – Pieter
    Nov 6, 2008 at 13:28
  • @Pieter: I propose you file that as an Answer, although it is not the answer that I was hoping for =-( Nov 6, 2008 at 13:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.