cfloat: Generalize double_format to allow specifying precision.
[altfloat.git] / cfloat.c
blob479d59c3dd9a1711dc2f86c23b3a756ec352dc4d
1 /*
2 * Floating point functions that are difficult or impossible to implement
3 * in pure Haskell.
5 * Copyright (C) 2009 Nick Bowler.
7 * License BSD2: 2-clause BSD license. See LICENSE for full terms.
8 * This is free software: you are free to change and redistribute it.
9 * There is NO WARRANTY, to the extent permitted by law.
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <errno.h>
14 #include <math.h>
16 #include "cfloat.h"
18 int double_format(char *buf, char spec, int precision, double val)
20 char fmt[] = "%.*f";
21 fmt[3] = spec;
23 if (buf == NULL)
24 return snprintf(NULL, 0, fmt, precision, val);
25 return sprintf(buf, fmt, precision, val);
28 double double_signum(double val)
30 if (signbit(val))
31 return -1;
32 return 1;
35 float float_signum(float val)
37 if (signbit(val))
38 return -1;
39 return 1;
42 int double_classify(double val)
44 switch (fpclassify(val)) {
45 case FP_INFINITE:
46 return 0;
47 case FP_NAN:
48 return 1;
49 case FP_NORMAL:
50 return 2;
51 case FP_SUBNORMAL:
52 return 3;
53 case FP_ZERO:
54 return 4;
57 return -1;
60 int float_classify(float val)
62 switch (fpclassify(val)) {
63 case FP_INFINITE:
64 return 0;
65 case FP_NAN:
66 return 1;
67 case FP_NORMAL:
68 return 2;
69 case FP_SUBNORMAL:
70 return 3;
71 case FP_ZERO:
72 return 4;
75 return -1;
78 int double_compare(double a, double b)
80 if (isless(a, b))
81 return 0;
82 if (a == b)
83 return 1;
84 if (isgreater(a, b))
85 return 2;
86 if (isunordered(a, b))
87 return 3;
88 return -1;
91 int float_compare(float a, float b)
93 if (isless(a, b))
94 return 0;
95 if (a == b)
96 return 1;
97 if (isgreater(a, b))
98 return 2;
99 if (isunordered(a, b))
100 return 3;
101 return -1;