Setting minimum number of decimal places for std::ostream precision

家住魔仙堡 提交于 2021-02-18 10:12:26

问题


Is there a way to set the "minimum" number of decimal places that a std::ostream will output?

For example, say I have two unknown double variables that I want to print (values added here for the sake of illustration):

double a = 0;
double b = 0.123456789;

I can set my maximum decimal precision so that I output b exactly

std::cout << std::setprecision(9) << b << std::endl;
>>> 0.123456789

Is there a way to set a "minimum" precision (a minimum number of decimal places), while retaining the "maximum" precision, so that

std::cout << a << std::endl << b << std::endl;

yields

0.0
0.123456789

not

0
0.123456789

?

Thanks! Phil


the short answer to this is "No". The stream has only one precision setting, with no facility to differentiate between maximum and minimum precision. Thanks all for your generous advice!


回答1:


I do not think there is a way to achieve what you are asking without turning the number into a string (with high precision), and stripping off the trailing zeros.

This is appropriate, because just because there are trailing zeros doesn't mean there isn't precision there, and the run-time can't tell that.

For example, if I measure the weight of an object with a cheap scale, it may be 1.0 kgs.

If I weigh it with a high-accuracy scale, it may be 1.00000 kgs. Just because there are trailing zeros, doesn't mean that accuracy should be discarded.




回答2:


cout << setprecision(1) << fixed << d << endl;

Used fixed after setprecision.

Edit: This is what you want. It would change precision based on d.

cout << setprecision(d?9:1) << fixed << d << endl;


来源:https://stackoverflow.com/questions/2489627/setting-minimum-number-of-decimal-places-for-stdostream-precision

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