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
?
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
?
How to convert
float
toint
according to the current rounding direction?
Create a helper function that calls lrintf()
and add desired error handling per C spec: "If the rounded value is outside the range of the return type, the numeric result is unspecified and a domain error or range error may occur.".
I recommend against using irintf()
in case that comes out later.
#incldue <errno.h>
#include <limits.h>
int my_irintf(float x) {
long y = lrinf(x);
// Add desired error handling here when int/long ranges differ.
#if LONG_MAX > INT_MAX || LONG_MIN < INT_MIN
// Example
if (y > INT_MAX || y < INT_MIN) {
errno = ERANGE;
y = (y > INT_MAX) ? INT_MAX : INT_MIN;
}
#endif
return (int) y;
}
Some systems raise FE_INVALID
like:
if (y > INT_MAX || y < INT_MIN) {
fesetexcept(FE_INVALID);
y = (y > INT_MAX) ? INT_MAX : INT_MIN;
}
Given implementation defined functionality with lrintf()
on errors, my_irintf(float x)
could benefit with likewise conditional code per implementation.
Why there is no version for
int
?
No strtoi()
exists in the standard library either. I suspect for similar reasons.
See Why is there no strtoi in stdlib.h?.
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;
}