I\'m trying to compare two strings, but I fail achieving that. Why?
#include
#include
int main(){
float a = 1231.23123;
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
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);
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".
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).