pierre tautou
pierre tautou

Reputation: 817

c function to round half down

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

Answers (5)

Lior Kogan
Lior Kogan

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

datenwolf
datenwolf

Reputation: 162367

Try roundf(float) or round(double)

Upvotes: -1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272802

Building on @jtniehof's answer.

ceil(x - 0.5)

This will always round halves down.

Upvotes: 2

jtniehof
jtniehof

Reputation: 601

Idiomatic way:

int j;
float i = 0.49;
j = (int)(i + 0.5);

Two caveats:

  1. 0.5 will always round up
  2. 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.

Upvotes: 1

Heisenbug
Heisenbug

Reputation: 39204

Have a look to round functions in math library.

Upvotes: 1

Related Questions