问题
The following code will print value of a and b:
double a = 3.0, b=1231231231233.0123456;
cout.setf(std::ios::fixed);
cout.unsetf(std::ios::scientific);
cout << a << endl << b << endl
The output is:
3.000000
1231231231233.012451
You can see that a is outputed with fixed 6 count of decimals. But I want the output like this:
3
1231231231233.012451
How can i set flags only once, and output the above result.
回答1:
The stream inserts 0
s following the double because the stream's default precision for the output of floating-point values is 6. Unfortunately there is no straightforward way of checking if the double represents a whole number (so you could then only print the integral part). What you could do however is cast the value to an integer.
std::cout << static_cast<int>(a);
回答2:
The default formatting for floating point numbers won't support the formats as requested. There are basically three settings you could use:
std::fixed
which will useprecision()
digits after the decimal point.std::scientific
which will use scientific notation withprecision()
digits.std::defaultfloat
which will choose the shorter of the two forms.
(there is also std::hexfloat
but that just formats the number in an form which is conveniently machine readable).
What you could do is to create you own std::num_put<char>
facet which formats the value into a local buffer using std::fixed
formatting an strips off trailing zero digits before sending the values one.
来源:https://stackoverflow.com/questions/20985769/c-stdstream-double-values-no-scientific-and-no-fixed-count-of-decimals