c function to round half down
I'm searching a function (in C language) which provi开发者_如何学编程de round half down. For example:
1.5 after round half down = 1 1.49999999 after round half down = 1 1.50000001 after round half down = 2
Building on @jtniehof's answer.
ceil(x - 0.5)
This will always round halves down.
Have a look to round functions in math library.
Idiomatic way:
int j;
float i = 0.49;
j = (int)(i + 0.5);
Two caveats:
- 0.5 will always round up
- The float representation in binary is not always what you expect in decimal. 0.5 is representable exactly; 0.3 is not. Shouldn't be a problem in this case but always work keeping in mind for corner-cases.
EDIT: Three caveats...definitely wrong for negative numbers. If you're doing anything at all complicated, definitely do look at the round functions in the math library, since they've handled the corner cases. But if quick-and-dirty is needed on limited input, this saves linking the math library.
Try roundf(float)
or round(double)
double RoundHalfDown(double f)
{
double int_part;
double frac_part = modf(f, &int_part);
if (frac_part <= -0.5) return int_part - 1.0;
if (frac_part <= 0.5) return int_part ;
return int_part + 1.0;
}
精彩评论