i want to check if a float is equal to another but only X number after the dot. For X = 3: 0.1234 == 0.1235
if (float1.X == float2.X)
do something
else
do something
i want to check if a float is equal to another but only X number after the dot. For X = 3: 0.1234 == 0.1235
if (float1.X == float2.X)
do something
else
do something
Floating point calculations are imprecise may lead to surprising rounding errors: Therefore I'll recommend that you avoid floating point calculations before comparing the fractional part.
Instead use sprintf
to print the values to strings. Then compare the number of decimals you want in the two stings. Make sure to use a sufficiently large width specifier to avoid unexpected roundings. For IEEE 754 32 bit floats the maximum number of decimals will be a little less than 150.
Start with:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
float f1 = 1.23456;
float f2 = 1.23457;
char str_f1[512];
char str_f2[512];
sprintf(str_f1, "%.160f", f1);
printf("%s\n", str_f1);
sprintf(str_f2, "%.160f", f2);
printf("%s\n", str_f2);
// Add code for string compare using X decimals
return 0;
}
Output:
1.234560012817382812500000000000000000000000000000000000000000...
1.234570026397705078125000000000000000000000000000000000000000...
So str_f1
and str_f2
are now two simple strings so you it's easy to compare them with exactly the number of decimals that you want.
This isn't exactly what you asked, but if you're trying to determine whether float1
and float2
are approximately equal, to within X significant digits, the usual way to do it is to subtract the two numbers, and see if the difference is less than a threshold. (And, of course, you have to take the absolute value into account.) So, for three significant digits, something like this:
if(fabs(float1 - float2) < 0.001)
do something;
else
do something else;
Or, to do it with a variable X
:
if(fabs(float1 - float2) < pow(10, -X))
do something;
else
do something else;