In C float is a data type that represents floating point numbers, using 32 bits. We use this type more often than double, because we rarely need the double’s precision.
int main() { float price = 5.50f; printf("The current price is %f.", price); return 0; }
A float value normally ends with the data specifier "f". If we leave it out, the literal(5.50) will be treated as double by default. You can do this and try to assign the value to a float variable. Most compilers will not issue a warning or an error. However, data will be lost if you try to enter a value with bigger precision than float can handle(more on this in a second). It is a good practice to explicitly set the specifier.
float distance = 5.12; // Should be avoided float fraction = 5.23f; // This one is prefeered
Further, will you see that the specifier for printing floats is %f.
The specifier for printing and scanning float values is the same %f.
We can specify the precision of the output. To do this, we write:
[integer part][.][fraction part]
In the next example (%.2f) we will print the value with precision two digits after the decimal mark.
int main() { float balance = 1000.55753f; float amount; printf("Your balance: $%.2f\n", balance); printf("How much would you like to withdraw?"); scanf("%f", &amount); if(amount > 0 && amount <= balance) { balance = balance - amount; } printf("The new balance is $%.2f", balance); return 0; }
The C standard does not explicitly specify the precision that needs to be supported. However, most C compilers use the IEEE 754 standard for encoding the float values. According to it, the single precision (float) is represented by 32 bits as follows:
This allows you to save up to 8 digits, including to the left and right of the fraction delimiter.
As you can see in the example above(source on GitHub), the following values can be saved without a problem
The following values will overflow the C float type and you will lose data as as a result:
See also: double data type