C float data type - single precision

    In C, the float data type represents floating point numbers, using 32 bits. We use this type more often than the double, because we rarely need the double’s precision.

Do you learn better from video?

Learn faster with deeper understanding!
The "Computer programming for beginners" course is the perfect place to begin with programming.

Start now!

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 letter ‘f’. If we leave it out the literal(5.50) will be treated as double by default. Further, 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 add the decimal delimiter ‘.’, followed by a number. This is the number of digits after the decimal mark that will be used as a precision. 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("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;
    }

Representation

    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


See also: double data type

Previous keywordextern

Next keywordfor loop

Do you learn better from video?

Learn faster with deeper understanding!
The "Computer programming for beginners" course is the perfect place to begin with programming.

Start now!


› float

Did this help? Support me with your vote ;-)

Did this help?