Reputation: 2181
I'm trying to compare two strings, but I fail achieving that. Why?
#include <stdio.h>
#include <string.h>
int main(){
float a = 1231.23123;
char b[32];
sprintf(b, "%f", a);
printf("%s\n", b);
char c[32] = "1231.23123";
if (strcmp(c, b) == 0){
printf("SUCCES\n");
}
else{
printf("DIFFER\n");
}
return 0;
}
Result:
1231.231201
DIFFER
Upvotes: 1
Views: 13203
Reputation: 42083
You are comparing these 2 strings here:
1231.23123
1231.231201
which are different indeed, thus strcmp
returns non-zero value.
The actual problem here is that when you do float a = 1231.23123;
, the number you want to store in a
can't be represented as a float
, the nearest number that can be represented as a float
is 1231.231201171875
in this case. Have a look at OMG Ponies!!! (Aka Humanity: Epic Fail) ;)
To solve your problem I would start with using double
instead of float
to get more precise accuracy. Then you could specify the precision (%.5lf
) while printing this number into the string to make sure that the number is rounded just like you need it:
double d = 1231.23123;
char str[32];
sprintf(str, "%.5lf", d);
// strcmp(str, "1231.23123") would return 0 here
Upvotes: 2
Reputation: 8195
If you want a set number of digits to compare against in a string, use the precision specifier in sprintf
- %.5f
, and as others have pointed out, the number you've picked cannot be represented by a float
, but can be represented by a double
. i.e.
double a = 1231.23123;
char b[32];
sprintf(b, "%.5f",a);
Upvotes: 4
Reputation: 500357
The two strings are clearly different, so strcmp()
is working as it should.
The issue is that 1231.23123
cannot be represented as a float
. In fact, the nearest number that can be represented as a float
is 1231.231201171875
, which is what you're seeing (rounded by sprintf()
to six decimal places).
Upvotes: 10
Reputation: 139
It's because the precision of float cannot support so many digits. So b is not "1231.23123". In my test, it's "1231.231201".
Upvotes: 3