c++ std::stream double values no scientific and no fixed count of decimals

核能气质少年 提交于 2019-12-23 04:56:17

问题


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 0s 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 use precision() digits after the decimal point.
  • std::scientific which will use scientific notation with precision() 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!