How about this? fmod should return decimal places after the specified number of decimal places, so we can compare these two numbers to make sure they are equal.
int needsD1Decimals(float N, int D1, int D2) {
float pow1 = pow(0.1f, D1);
float pow2 = pow(0.1f, D2);
float mod1 = fmod(N, pow1);
float mod2 = fmod(N, pow2);
if (fabs(mod1 - mod2) > (pow1 / 2)) {
return 1;
}
return 0;
}
If you just want to print the correct answer, most likely just print it with the most decimal places and trim the zeros at the end:
void printNumber(float N, int D1, int D2) {
char format[256];
char result[256];
sprintf(format, "%%.%df", D1);
sprintf(result, format, N);
char *end = result + strlen(result) - 1;
int zeros = 0;
while (end > result && end[0] == '0' && zeros < (D1 - D2))
{
zeros++;
end--;
}
if (zeros >= (D1 - D2))
{
end[1] = '\0';
}
puts(result);
}
void doNumber(float N, int D1, int D2) {
printf("%f, %d, %d: ", N, D1, D2);
printNumber(N, D1, D2);
printf("\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
doNumber(0.01001f, 4, 2);
doNumber(0.010101f, 4, 2);
doNumber(0.011001f, 4, 2);
doNumber(5000.0f, 4, 2);
return 0;
}