Thursday, April 6, 2017

float to int...Interesting difference between TYPECASTING and Ceiling/Flooring/Truncating/Rounding

int a;
float b = 3.45f;
b = b * 3.142f;  /* which is 10.8399
a = (int)b;
printf("%f, %d", b,  a);

here b = 10.8399 and a = 10

this above mentioned method is where, typecasting is used for float to int conversion.
This is not the right way always.
Because it depends on the standards that are used when writing the compiler. How compiler will replace this conversion process.
Usually in C99, it uses truncation when converting float to int. But its not usually desirable, as you can see in the above example use expect it would be 11 rather than 10.

So, in these scenarios one should always use float to int conversion method as per the requirement of the application. There are functions readily available in math.h

  1. ceiling: eg. 10.78-> 11; 10.44 -> 11; 7.5->8; -11.89 -> -11; -11.14->-11; -7.5 -> -7
  2. flooring: eg. 10.78-> 10; 10.44 -> 10; 7.5->7; -11.89 -> -12; -11.14->-12;  -7.5 -> -8
  3. truncating: eg. 10.78-> 10; 10.44 -> 10; 7.5->7; -11.89 -> -11; -11.14->-11; -7.5 -> -7
  4. rounding: eg. 10.78-> 11; 10.44 -> 10; 7.5 -> 8; 8.5->9; -11.89 -> -12; -11.14->-11; -7.5 ->-8; -8.5->-9
  5. rounding even:  eg. 10.78-> 11; 10.44 -> 10; 7.5 -> 8; 8.5->8; -11.89 -> -12; -11.14->-11; -7.5 -> -8; -8.5->-8
I think this is a very important point when your application is demanding precision. Hope it helps

No comments:

Post a Comment

PROFILE

My photo
India
Design Engineer ( IFM Engineering Private Limited )

Followers