Reputation: 2299
I have some float
variables that would yield values like 1.23456789. I want to round it off to, say 4 decimal places.
the setprecision function only roundoffs output, but I want to change the value of variable itself.
So I'm looking for something like
x=roundoff(x,n)
where roundoff will round off x to n decimal places.
Upvotes: 3
Views: 11366
Reputation: 10132
This is kind-of OK with double, less accurate with float. Personally if I want to specify numbers to some fixed precision, I usually use some kind of fixed point notation (integer + divisor).
#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);
}
For double the result of the above is 1000.123000000, with float it's 1000.12299.
Upvotes: 7
Reputation: 1299
Why not this?
float val = 1.23456789
float rounded_down = floorf(val * 1000) / 1000; /* 1.2345 */
EDIT:
as pointed out in the comments keep in mind that this is an approximation, but it might be acceptable in many situations. Also yo might want to round to the nearest value or to round up as follows:
float val = 1.23456789
float near = roundf(val * 1000) / 1000; /* nearest */
float up = ceilf(val*1000) / 1000; /* up*/
Upvotes: 5
Reputation: 12098
float roundoff(float value, unsigned char prec)
{
float pow_10 = pow(10.0f, (float)prec);
return round(value * pow_10) / pow_10;
}
Keep in mind, that in some cases, result will not be always the exact one, because of how floating-point numbers are represented in memory.
Upvotes: 2