Reputation: 817
I'm searching a function (in C language) which provide 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
Upvotes: 1
Views: 1257
Reputation: 20668
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;
}
Upvotes: 0
Reputation: 272802
Building on @jtniehof's answer.
ceil(x - 0.5)
This will always round halves down.
Upvotes: 2
Reputation: 601
Idiomatic way:
int j;
float i = 0.49;
j = (int)(i + 0.5);
Two caveats:
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.
Upvotes: 1