function to round a float to an int?

F

fdunne2

Is there a function in C that rounds off a float to an int?
e.g. 8.968 -> 9 or 3.217 -> 3.

Regards,
F.
 
N

nrk

pete said:
Look up ceil() and floor(), from math.h

Neither of which do what the OP wants. Perhaps something like:

double f; /* to be rounded */
....

int i = ( f < 0 ) ? f - 0.5 : f + 0.5;

with some care to avoid integer overflow?

-nrk.
 
T

Tim Prince

fdunne2 said:
Is there a function in C that rounds off a float to an int?
e.g. 8.968 -> 9 or 3.217 -> 3.

Regards,
F.
This group is about standard C. Standard C has included functions such as
lrint() for nearly 4 years now.
 
W

William Hughes

nrk said:
Neither of which do what the OP wants. Perhaps something like:

double f; /* to be rounded */
...

int i = ( f < 0 ) ? f - 0.5 : f + 0.5;

with some care to avoid integer overflow?

Or perhaps floor(f + 0.5) returning a double and
avoiding overflow problems. C99 provides round() and nearbyint().

If there is a significant chance of having f exactly half
way between two integers (f=x.5), then
you may need to round half way cases
to the nearest even integer (i.e. banker's rounding).
Usually you can ignore this refinement.

- William Hughes
- William Hughes
 
D

Dan Pop

This group is about standard C.

Last time I checked, K&R C was still topical.
Standard C has included functions such as lrint() for nearly 4 years now.

Which is of little help if the OP's implementation is not conforming to
the latest C standard (the vast majority of C implementations in current
use aren't).

Dan
 
Joined
Jul 19, 2011
Messages
1
Reaction score
0
pete wrote:

> fdunne2 wrote:
>>
>> Is there a function in C that rounds off a float to an int?
>> e.g. 8.968 -> 9 or 3.217 -> 3.

>
> Look up ceil() and floor(), from math.h
>


Neither of which do what the OP wants. Perhaps something like:

double f; /* to be rounded */
....

int i = ( f < 0 ) ? f - 0.5 : f + 0.5;

with some care to avoid integer overflow?

-nrk.

--
Remove devnull for email
The Real one for this round function is this one given below
int intnum,num;
float floatnum;
num=(int)(floatnum+0.5);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top