简体   繁体   中英

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. ie: 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?

Can't you just round it.

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

The precision of float and double is down to the hardware. Anything else needs to be coded in software.

You could try scaling instead, working in ints:

-205
 -10
  30
  14
 141
 -17
  55
  36

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM