设置std :: ostream精度的最小小数位数 [英] Setting minimum number of decimal places for std::ostream precision

查看:371
本文介绍了设置std :: ostream精度的最小小数位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以设置std :: ostream输出的最小"小数位数?

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;

我可以设置最大十进制精度,以便准确地输出 b

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;

收益

0.0
0.123456789

不是

0
0.123456789

?

谢谢!菲尔

对此的简短回答是否".数据流只有一个精度设置,无法区分最大精度和最小精度.谢谢大家的慷慨建议!

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!

推荐答案

我不认为有一种方法可以将数字转换为字符串(高精度)并且去除尾随的零,从而实现您所要的内容

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.

例如,如果我用便宜的秤来测量物体的重量,则可能是1.0公斤.

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

如果我用高精度秤称量它,可能是1.00000公斤.仅仅因为尾随零,并不意味着应该放弃准确性.

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.

这篇关于设置std :: ostream精度的最小小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆