# C float data type - single precision

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.

Advertise on this site. I promise you will like the rates :)

## C float - usage example

```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.

## Scanning floats and specifying printing precision

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]

• The integer part is optional. Usually it will be ignored.
• The decimal delimiter ‘.’ must be used if we intend to print from the fraction.
• It specifies how many of digits from the fraction should be printed. When the actual value has longer precision, it will be rounded for the printing purposes.

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("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;
}
```

## Representation

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: • 1 sign bit
• 23 bits of significand
• 8 bits of exponent

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

• 1234567.0
• 1234.5678
• 0.1234567

The following values will overflow the C float type and you will lose data as as a result:

• 12345678.0
• 1234.56789
• 0.12345678