Gaijinco said:
Sooner or later everytime I found recreational programming challenges I
stumble with how I test if a number is has decimal places differnt than
0?
If we know the internal representation of the double, we can use that
information. But I'm not sure if that detail is implementation
specific.
We can use snprintf routine to get a textual representation of the
double
and look to see if the decimal part is zero. Something like,
#include <stdio.h>
#include <stdlib.h>
/*
* 1 if d is has decimal part zero
* 0 if d has non zero decimal part
* -1 error
*/
int
is_double_integer (double d)
{
int buff_size;
char *buff, *p_dot, *p;
buff_size = snprintf(NULL, 0, "%.16f", d);
if (buff_size < 0) return -1;
buff = malloc(buff_size + 1);
if (!buff) return -1;
snprintf(buff, buff_size+1, "%.16f", d);
p_dot = strchr(buff, '.');
if (!p_dot) {
free(buff);
return -1;
}
for (p = p_dot+1; *p; ++p) {
if (*p != '0') {
free(buff);
return 0;
}
}
free(buff);
return 1;
}
int main (void)
{
double d = 23.2342443400000001;
printf("[%f] : is decimal part zero? [%d]\n", d,
is_double_integer(d));
d = 12323.00000000001;
printf("[%f] : is decimal part zero? [%d]\n", d,
is_double_integer(d));
d = 12323.00000000000000;
printf("[%f] : is decimal part zero? [%d]\n", d,
is_double_integer(d));
return 0;
}
$>./a.out
[23.234244] : is decimal part zero? [0]
[12323.000000] : is decimal part zero? [0]
[12323.000000] : is decimal part zero? [1]
Karthik