2015-04-04 320 views
0

我有一些float变量会产生像1.23456789这样的值。我想把它四舍五入到小数点后四位。如何在C++中将变量四舍五入到小数点后n位

setprecision函数只是舍入输出,但我想更改变量本身的值。

所以我在寻找类似

x=roundoff(x,n) 

,其中舍入将四舍五入X到n位小数。

+2

对于某些值,这是不可能的。 – usr2564301 2015-04-04 14:36:20

+0

@Jongware可以请你详细说明一下吗? – 2015-04-04 14:37:57

+0

近似值可以是round(x * tenToTheNth)/ tenToTheNth,但请记住,由于浮点数的性质,这通常不会给出精确的值。 – 2015-04-04 14:39:19

回答

1

为什么不呢?

float val = 1.23456789 

    float rounded_down = floorf(val * 1000)/1000; /* 1.2345 */ 

编辑:

在评论中指出记住,这是一个近似,但它可能在很多情况下是可以接受的。 还哟可能要舍入到最接近值或围捕如下:

float val = 1.23456789 

    float near = roundf(val * 1000)/1000; /* nearest */ 
    float up = ceilf(val*1000)/1000; /* up*/ 
3

这双,少用浮准确那种-的确定。就个人而言,如果我想指定一些固定精度的数字,我通常会使用某种定点符号(整数+除数)。

#include <cmath> 

template<class T> 
static T Round(T a) 
{ 
    static_assert(std::is_floating_point<T>::value, "Round<T>: T must be floating point"); 

    return (a > 0) ? ::floor(a + static_cast<T>(0.5)) : ::ceil(a - static_cast<T>(0.5)); 
} 

template<class T> 
static T Round(T a, int places) 
{ 
    static_assert(std::is_floating_point<T>::value, "Round<T>: T must be floating point"); 

    const T shift = pow(static_cast<T>(10.0), places); 

    return Round(a * shift)/shift; 
} 

int main() 
{ 
    auto x = -1000.123; 
    auto result = Round(x, 3); 
} 

对于double的结果是1000.123000000,其中float是1000.12299。

0
float roundoff(float value, unsigned char prec) 
{ 
    float pow_10 = pow(10.0f, (float)prec); 
    return round(value * pow_10)/pow_10; 
} 

请记住,在某些情况下,由于浮点数在内存中的表示方式,结果并不总是精确的。

相关问题