I have a program in C that has to remove all decimal places of a variable by multiplying it with 10^(numberOfDecimalPlaces)
. I have written the following function to count decimal places:
int getDecimalPlaces(double n)
{
int numberOfDecimalPlaces = 0;
for (numberOfDecimalPlaces = 0; n != (int) n; n *= 10)
numberOfDecimalPlaces++;
return numberOfDecimalPlaces;
}
The problem is that when I am passing 1.4
to the function, it handles it as 1.399999999...
because of floating point arithmetic. Do you know a way to still count the number of decimal places with a simple algorithm without having to worry about floating point precision? Thanks in advance. Using sprintf
, that can be fixed.
#define MAX_STRING 256
typedef enum
{
false, true
} bool;
int getDecimalPlaces(double n)
{
char string[MAX_STRING];
sprintf(string, "%f", n);
int numberOfDecimalPlaces = 0;
int i; // index of \0
for (i = 0; i < MAX_STRING; ++i)
if (string[i] == '\0')
break;
bool countZero = false;
for (int j = i-1; j > 0; j--)
{
if (string[j] == '.')
break;
if (!countZero && string[j] != 48)
countZero = true;
if (countZero)
numberOfDecimalPlaces++;
}
return numberOfDecimalPlaces;
}