4

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 ?

Ælex
  • 14,432
  • 20
  • 88
  • 129
  • possible duplicate of [Rounding Number to 2 Decimal Places in C](http://stackoverflow.com/questions/1343890/rounding-number-to-2-decimal-places-in-c) – Greg Hewgill Jul 11 '11 at 23:25

2 Answers2

6

Can't you just round it.

float round(float num, int precision)
{
    return floorf(num * pow(10.0f,precision) + .5f)/pow(10.0f,precision);
}
Sophy Pal
  • 435
  • 2
  • 7
  • This is so funny. Your floats are held with a precision fixed by the implementation. If you want exact values use integers. Otherwise you should just be rounding the values when printing and the output functions have this built in. – Martin York Jul 11 '11 at 23:51
  • I have no idea what you just said Martin. Care to explain ? As I said i am not interested in printing values, but rounding them to a 2 point precision and comparing them. – Ælex Jul 12 '11 at 00:33
2

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
MRAB
  • 20,356
  • 6
  • 40
  • 33
  • I have thought about scalling, but it isn't enough accurate either. If for example the range of an actuator is -1.50 up to 3.50, I only need the two decimal range, anything more is just adding noise, anything less is generalizing too much. – Ælex Jul 11 '11 at 23:33