I am writing some C code to repeatedly round floats up and down to integer values.
The standard C math library includes the functions floor()
and ceil()
.
I noticed that a much quicker implementation of the functions is to cast directly to integers:
int up, down;
float test = 1.3548;
up = (int)(test + 1); //ceil()
down = (int)test; //floor()
I did a quick check and this seems to work fine.
The functions ceil()
and floor()
will return different numbers than what you get by using
up = (int)(test + 1);
down = (int)test;
when you have a negative number.
If you have:
float test = -1.3548;
up = (int)test; // ceil()
down = (int)(test-1); // floor()
Even the last statement is not a good way to compute floor()
when test
is an integral number.
Unless you want to deal with positive and negative numbers differently, and the special cases of when test
is integral number, you are better off using ceil()
and floor()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With