Files
42_INT_01_libft/srcs/ft_round.c
2026-05-07 00:58:54 +02:00

28 lines
678 B
C

#include "libft.h"
/**
* round x to the nearest integer,
* but round halfway cases away from zero, regardless of the current rounding direction
*/
double ft_round(double x)
{
// Handle special cases
if (x != x)
{ // Check for NaN (NaN is not equal to itself)
return x; // Return NaN
}
if (x == (double)LLONG_MAX + 1.0 || x == (double)LLONG_MIN - 1.0)
{
return x; // Return ±Infinity or the original value if overflow would occur
}
// Handle positive and negative numbers
if (x >= 0)
{
return (double)(long long)(x + 0.5);
}
else
{
return (double)(long long)(x - 0.5);
}
}