c++boostroundingnumeric-conversion

C++ how to set a fixed decimal precision for a float


I have an API call which returns a double. The double's decimal length can variate from many decimal places to a few (it all comes down to the state of an actuator). This double represents the current position on the range radius of an actuator. I am not interested in such a detailed number, because it adds alot of noise to the system. I've been using floats to save space, but still I have floats which have 6-8 decimal length. I am not interested in floor or ceil, simply because it doesn't do the job i want. For example, I have the numbers:

-2.05176
-0.104545
 0.30643
 0.140237
 1.41205
-0.176715
 0.559462
 0.364928

I want the precision to be set to 2 decimal places no matter what. I am NOT talking about the output precision on std::cout, I know how to set this. I am talking about the actual precision of the float. i.e: I am interested in floats who will have 0.XX format and 0.XX00000000000 actual precision. Therefore transforming the above list to:

-2.05
-0.10
 0.30
 0.14
 1.41
-0.17
 0.55
 0.36

I know boost has a numerical conversion template, but I cannot figure out how to convert from float to float using a lower precision. Can somebody please help ?


Solution

  • Can't you just round it.

    float round(float num, int precision)
    {
        return floorf(num * pow(10.0f,precision) + .5f)/pow(10.0f,precision);
    }