0

I have a rounding function,

float myround(float x, int places)
{
   float const shift = powf(10.0f, places);
   x *= shift;
   x = floorf(x + 0.5f);
   x /= shift;

   return x;
}

When I try to round of numbers to lets say 4 decimal places and then print the number with

printf("%f ", x); 

I get the number without rounding. If I print it with

printf("%.4f ", x);

I get the number rounded to 4 places. Should the first printf not print the number to 4 decimal places as I have already rounded the number?

Thanks.

rudasi
  • 185
  • 2
  • 14
  • possible duplicate of [Is there a function to round a float in C or do I need to write my own?](http://stackoverflow.com/questions/497018/is-there-a-function-to-round-a-float-in-c-or-do-i-need-to-write-my-own) – msw May 20 '13 at 22:00
  • 1
    `floorf(x + 0.5f)` sometimes does not return the nearest integer. `roundf(x)` would be better. http://blog.frama-c.com/index.php?post/2013/05/02/nearbyintf1 – Pascal Cuoq May 20 '13 at 22:01
  • 1
    Here's an exercise: Try to write down 0.002 (base 10) as a base-2 (i.e. binary) floating point number with finite number of discrete digits. I save you the effort: You can't do it, 0.002 (base 10) can not be represented as a binary number with a finite amount of bits. By this single counterexample it should become clear, that you can't "round" every float to a finite number of base 10 digits. – datenwolf May 20 '13 at 22:15

2 Answers2

2

You can't round floats, you can only print them to a specific precision. All floats are always "unrounded", although you can obviously change the value to more closely approximate a rounded amount.

Crowman
  • 25,242
  • 5
  • 48
  • 56
0

From man printf

f, F   The double argument is rounded and converted to decimal notation in the style [-]ddd.ddd, where the number of digits after the decimal-point character is equal to the precision
       specification. If the precision is missing, it is taken as 6; if the precision is explicitly zero, no decimal-point character appears. If a decimal point  appears,  at  least one
       digit appears before it.

The fprintf(), printf(), sprintf(), vprintf(), vfprintf(), and vsprintf() functions conform to C89 and C99.

So, no, it should not do anything other than take 6 as the precision if you don't supply it.

mvds
  • 45,755
  • 8
  • 102
  • 111