#include<stdio.h>
int main(){
float x =5400.768;
printf("%f", x);
}
In the above code, once I execute the program it will display 5400.768066 as output with 3 extra decimal places. Why is that?
#include<stdio.h>
int main(){
float x =5400.768;
printf("%f", x);
}
In the above code, once I execute the program it will display 5400.768066 as output with 3 extra decimal places. Why is that?
The problem is floating point inaccuracy. Basically, the number is stored in 32 bits, which can only contain a finite amount of precision, and usually only have ~7 decimal digits of precision. If you need more accuracy you could use a 64-bit value (aka double
).
Have a look at this https://m.youtube.com/watch?v=f4ekifyijIg if you wanna know how floats
are stored in memory.
If you want to print just to 3 decimal places, use printf("%.3f",variable_name);
.