I’m trying to extract the first digit of an interger. For that I take the number, divide it by 10, and then substract the interger part of that number, resulting in only the decimal part, wich is then multiplied by 10, and voila, the first digit of the interger.
Now the problem. The code works for all digits except 2 and 7, giving 1 and 6 respectively as result. I imagine it is related to floating point errors, like it represents 0.2 and 0.7 as 0.19999 and 0.69999. When debugging it shows the correct values but the substraccion result is incorrect. I’m not sure how to solve or approach this issue, any help is welcomed. Thanks beforehand.
The compiler I’m using is gcc.
The section of the code related to this problem is:
temp_number = (double)number / 10;
number = trunc(temp_number);
digit = (temp_number - number) * 10;
And the rest, for context, if it is needed:
bool get_checksum(long number, int number_lenght)
{
bool checksum = 0;
int total;
int digit;
double even = 0;
double odd = 0;
double temp_number;
for (int i = 1; i <= number_lenght; i++)
{
temp_number = (double)number / 10;
number = trunc(temp_number);
digit = (temp_number - number) * 10;
if (i % 2 == 0)
{
digit *= 2;
even += digit / 10;
even += ((float)digit / 10 - digit / 10) * 10;
}
else
{
odd += digit;
}
}
total = even + odd;
if (total % 10 == 0)
{
checksum = 1;
}
return checksum;
}