C ++中小数点的位数限制 [英] Digit limitation from decimal point in C++

查看:476
本文介绍了C ++中小数点的位数限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手。我有一个双精度变量 double a = 0.1239857 ,我想将变量 a 限制为小数点后两位数字。因此 a 将为 0.12 。我知道C ++具有返回大于或小于 a 的最大或最小整数的函数,例如ceil或floor。

I'm new to C++. I have a double variable double a=0.1239857 and I want to limit variable a from decimal point two digits. So a will be 0.12. I know C++ have functions that return largest or smallest integer that is greater or lower than a like ceil or floor.

是否存在一个函数实现浮点变量的数字限制?或如何更改 a 变量的精度?

Is there a function that implements digit limitation of floating-point variable? Or How can I change precision of the a variable?

推荐答案

是您实际上是尝试舍入数字,还是只是更改其显示精度?

Are you actually trying to round the number, or just change its displayed precision?

对于前者(将多余的数字截断):

For the former (truncating the extra digits):

double scale = 0.01;  // i.e. round to nearest one-hundreth
value = (int)(value / scale) * scale;

或(根据jheriko的回答,四舍五入)

or (rounding up/down as appropriate, per jheriko's answer)

double scale = 0.01;  // i.e. round to nearest one-hundreth
value = floor(value / scale + 0.5) * scale;

对于后者:

cout << setprecision(2) << value;

其中 setprecision()的参数为小数点后显示的最大位数。

where the parameter to setprecision() is the maximum number of digits to show after the decimal point.

这篇关于C ++中小数点的位数限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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