Menu
Coddy logo textTech

Float - Double

Part of the Fundamentals section of Coddy's C journey — lesson 7 of 63.

Float and double are data types used to store decimal numbers in C.

Declare a float variable:

float price = 19.99f;

Notice the 'f' suffix, which tells C this is a float value.

Declare a double variable:

double pi = 3.14159265359;

The main differences between float and double:

  1. Precision: Double has higher precision than float
    • Float: ~7 decimal digits
    • Double: ~15 decimal digits
  1. Size:
    • Float: 4 bytes
    • Double: 8 bytes
  1. Range:
    • Float: 1.2E-38 to 3.4E+38
    • Double: 2.3E-308 to 1.7E+308

Print a float value:

float temperature = 98.6f;
printf("Temperature is %f degrees\n", temperature);

Print with specific decimal places:

printf("Temperature is %.1f degrees\n", temperature);

This will show: “Temperature is 98.6 degrees”

challenge icon

Challenge

Easy

Write a program that:

  1. Declares a float variable named celsius
  2. Declares a double variable named fahrenheit
  3. Assigns the value 25.0 to celsius
  4. Converts celsius to fahrenheit using the formula: fahrenheit = (celsius * 9.0/5.0) + 32.0
  5. Prints the result as
    25.0 degrees Celsius is equal to 77.0 degrees Fahrenheit

Make sure to display precisely one decimal place in your output. The spelling of Celsius and Fahrenheit must match exactly.

To print both variables in a single printf, use %.1f as a placeholder for each number. Replace celsius and fahrenheit with your actual variable names:

printf("%.1f degrees Celsius is equal to %.1f degrees Fahrenheit\n", celsius, fahrenheit);

Here, the first %.1f will be replaced by the value of celsius, and the second %.1f will be replaced by the value of fahrenheit. The \n at the end moves the cursor to a new line.

Cheat sheet

Float and double are data types for decimal numbers in C.

Declare a float variable (note the 'f' suffix):

float price = 19.99f;

Declare a double variable:

double pi = 3.14159265359;

Key differences:

  • Precision: Float (~7 digits), Double (~15 digits)
  • Size: Float (4 bytes), Double (8 bytes)
  • Range: Float (1.2E-38 to 3.4E+38), Double (2.3E-308 to 1.7E+308)

Print float values:

printf("Temperature is %f degrees\n", temperature);

Print with specific decimal places:

printf("Temperature is %.1f degrees\n", temperature);

Try it yourself

#include <stdio.h>

int main() {
    // Write your code here
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals