summaryrefslogtreecommitdiff
path: root/src/math/round.c
blob: 48260dd2f7c8d7e471dfa3fd9f46e2f852f7f738 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# define TGSOURCE "round.c"
#include "_tgmath.h"
#include <math.h>
#include <fenv.h>

#ifndef __GNUC__
#pragma STDC FENV_ACCESS ON
#endif

TYPE TGFN(round)(TYPE x)
{
	switch (fpclassify(x)) {
	case FP_ZERO:		return x;
	case FP_INFINITE:	return x;
	default:		break;
	}

	fenv_t save_env;
	feholdexcept(&save_env);

	TYPE ret = TGFN(rint)(x);

	if (fetestexcept(FE_INEXACT)) {
		fesetround(FE_TOWARDZERO);
		ret = TGFN(rint)(TGFN(copysign)(0.5 + TGFN(fabs)(x), x));
	}

	feupdateenv(&save_env);

	return ret;
}

/*
STDC(199901)
LINK(m)
*/