C ++中小数点的数字限制

时间:2009-04-28 13:51:12

标签: c++

我是C ++的新手。我有双变量double a=0.1239857我想限制变量a  从小数点后两位数。所以a将是0.12。我知道C ++的函数返回大于或小于a的最大或最小整数,如ceil或floor。是否有一个函数实现浮点变量的数字限制?或者我如何改变a变量的精度?

最好的问候......

9 个答案:

答案 0 :(得分:22)

您是否真的尝试对数字进行舍入,或者只是更改其显示的精度?

对于前者(截断额外数字):

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

或(根据jheriko的回答,适当地向上/向下舍入)

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

对于后者:

cout << setprecision(2) << value;

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

答案 1 :(得分:6)

这将导致小数点后两位数。

a = floor(a * 100.0) / 100.0;

答案 2 :(得分:3)

你想要限制变量是什么意思?值或其格式。对于该值,您可以使用floor + division。类似的东西:

double a = 0.12123
double b;

b = floor(a * 100) / 100

答案 3 :(得分:1)

如果您只想输出值,可以执行类似

的操作
printf("%.3f", a); // Output value with 3 digits after comma

如果您想转换价值本身,您可以这样做:

a = (int)(a * 1000) / 1000.0f;

请注意,两者都不进行舍入,只是截断值。

答案 4 :(得分:1)

使用ios_base::precision格式化i / o。

答案 5 :(得分:1)

您可以在流上设置精度,例如

double d = 3.14579;
cout.precision(2);
cout << d << endl;

// Or use a manipulator

#include <iomanip>
cout << setprecision(2) << d << endl;

请注意,当您将double或float发送到此类流时,它会自动为您舍入(如果您不知道这一点,有时可能会让您失望)。

答案 6 :(得分:1)

实际的舍入解决方案是x = floor(100*x + 0.5) / 100;,假设要舍入的值是变量“x”。

其他人推荐的x = floor(100*x) / 100;实际上会将数字截断为2dp。

答案 7 :(得分:1)

您也可以这样做:

//This code will ask the user for an input, set the decimal precision to the hundredths place,  and add 4.63 to the inputted variable

int banana;
cin >> banana;
cout << setprecision(2) << fixed << banana + 4.63; 

答案 8 :(得分:0)

您可以编写自己的函数如下,它也可以处理小数的舍入错误。

double RoundForGivenPrecision(const double dNumber, int iDecimalPlaces)
{
long long multiplier = (long long)pow(10, iDecimalPlaces);
long double value = dNumber < 0 ? (long long)((nextafter(dNumber, -DBL_MAX)*multiplier)-0.5) : (long long)((nextafter(dNumber,DBL_MAX)*multiplier)+0.5);
return value / multiplier;
}