Reputation: 63
I am using this code to output a scientific notation number to a file:
file << scientific << setprecision(10) << num << endl;
For example, if the number is 3.0, I get 3.0000000000E+00 from the code. How do I make the digits of the exponent part to be 3 digits? I want to get 3.0000000000E+000.
Upvotes: 3
Views: 3174
Reputation: 1811
It seems like as @Bob__ stated that visual studio used to have a function called: _set_output_format
which allowed you to change the exponent BUT this was removed in the Visual Studio 2015 version I believe.
As quoted in Portable printing of exponent of a double to C++ iostreams.
The
%e
and%E
format specifiers format a floating point number as a decimal mantissa and exponent. The%g
and%G
format specifiers also format numbers in this form in some cases. In previous versions, the CRT would always generate strings with three-digit exponents. For example,printf("%e\n", 1.0)
would print1.000000e+000
. This was incorrect: C requires that if the exponent is representable using only one or two digits, then only two digits are to be printed.In Visual Studio 2005 a global conformance switch was added:
_set_output_format
. A program could call this function with the argument_TWO_DIGIT_EXPONENT
, to enable conforming exponent printing. The default behavior has been changed to the standards-conforming exponent printing mode.
So in order to resolve your issue if you really want to write with a 3 digit exponent would be to modify the output. You can do so by transforming the double into a string, example:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
std::string getStrCpy(double dbl) {
std::ostringstream str;
str << std::scientific << std::setprecision(10) << dbl;
std::string s = str.str();
std::cout << s; // Prints 3.0000000000e+00
return s;
}
int main() {
double d = 3.0;
std::cout.precision(10);
std::cout << std::scientific;
std::cout << d << '\n'; // Prints 3.0000000000e+00
getStrCpy(d); // Will also print 3.0000000000e+00
return 0;
}
Now getStrCpy()
will return a string of the double you were trying to print which you can modify in order to add an extra number to your exponent.
Upvotes: 1