float to integer conditionally

I need to check if a float value is actually an integer. If so, I use the value as integer, otherwise as float.

How to implement it? I realized that I don’t know a standard function (neither in C, neither in Java and other languages). Fortunately, traces of education helped me to formulate a search query for Google and find the constants required.

The code fragment:

//
// Convert to a number
//
// from http://pigale.sourceforge.net/doc/Tbase_8h-source.html
// minimal double such that DBL_EPSILON + 1. != 1.
#ifndef DBL_EPSILON
#define DBL_EPSILON     2.22044604925031300e-016
#endif
if (XPATH_NUMBER == xobj->type) {
  double val = xobj->floatval;
  if ((0 == xmlXPathIsInf(val)) && (! xmlXPathIsNaN(val))) {
    int ival = (int)val;
    if (fabs(val - ival) < DBL_EPSILON) {
      return gh_int2scm(ival);
    } else {
      return gh_double2scm(val);
    }
  }
}

I'm ready for suggestions on a better variant.

2 Responses to “float to integer conditionally”

  1. sds Says:

    (defun float-integer-p (x) (= x (round x)))

  2. olpa Says:

    Thank you. It’s much simpler. No need for epsilon.

Leave a Reply