Home > database >  Check if float is equal to another X number after dot in C
Check if float is equal to another X number after dot in C

Time:01-19

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

CodePudding user response:

Any calculation that you do on the two variables may change the fractional value. So calculations are to be avoided.

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.

CodePudding user response:

The usual way to do this 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 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;

CodePudding user response:

You can do something like this:

#include <math.h>

int compare(float float1, float float2, int decimals) {
    double n = pow(10, decimals);
    return (int)(float1 * n) == (int)(float2 * n);
}

But keep in mind that by the definition of the floating-point standard, the decimal representation of a floating-point value is not guaranteed to be accurate to begin with.

  •  Tags:  
  • Related