How to convert float
to int
according to the current rounding direction?
There are the lrint
and llrint
functions (C11, 7.12.9.5). However, their return values have types long int
and long long int
. Why there is no version for int
?
Maybe because int
is quite small and you can easily write such a function yourself.
int irint(double x)
{
#if (LONG_MAX > INT_MAX && LONG_MIN < INT_MIN)
long result = lrint(x);
#else
long long result = llrint(x);
#endif
if(result > INT_MAX || result < INT_MIN)
{
feraiseexcept(FE_INVALID);
return 0;
}
return (int)result;
}