Educational Blog

How to Use double in C

Learn how to declare, print, compare, and use double values in C safely.

If you are learning C, double is one of the first numeric types worth understanding well. It looks simple on the surface: declare a variable, assign a decimal value, and use it in calculations. In practice, the details matter. double gives you more precision than float, but it also comes with tradeoffs in storage, formatting, comparison, and portability. That makes it a practical type, not just a syntax lesson.

This guide walks through what double is, when to use it, how to print it correctly, how to compare values safely, and what mistakes to avoid when you need reliable decimal math in C.

What double means in C

double is a floating-point type used to store numbers with fractional parts. It is designed for values such as temperatures, measurements, scientific calculations, currency approximations, and any other case where a whole number is not enough.

A simple example looks like this:

int main(void) {
    double price = 19.95;
    double tax = 1.55;
    double total = price + tax;

    printf("Total: %.2f
", total);
    return 0;
}

In this snippet, price, tax, and total are all double values. The %.2f format specifier prints two digits after the decimal point, which is helpful for human-readable output.

Why double is often preferred over float

Both float and double store approximate real numbers, but double usually gives you more precision. That extra precision matters when repeated calculations can accumulate error.

A rough comparison:

TypeTypical usePrecisionStorage
floatSmaller memory footprintLower4 bytes
doubleGeneral-purpose decimal mathHigher8 bytes
long doubleExtended precision, platform-dependentOften highestVaries

The exact size of double can vary by platform, but in most modern systems it is 8 bytes and follows IEEE 754 binary64 semantics.

Declaring and assigning double

You can declare a double with a decimal literal or with an integer literal. C will convert the integer to a floating-point value when needed.

double a = 3.14;
double b = 10;
double c = a + b;

You can also assign results from expressions:

double radius = 2.5;
double area = 3.141592653589793 * radius * radius;

A few habits help keep code clear:

  • Use descriptive variable names such as temperature, average, or distance.
  • Prefer decimal literals with an explicit fractional part when the value is meant to be floating-point.
  • Keep calculations grouped logically so the intent is easy to read.

The right way to print double

Printing double values is one of the most common places beginners make mistakes. In C, printf uses format specifiers, and double should generally be printed with %f or a precision variant such as %.3f.

#include <stdio.h>

int main(void) {
    double value = 12.3456789;
    printf("Default: %f
", value);
    printf("Two decimals: %.2f
", value);
    printf("Six decimals: %.6f
", value);
    return 0;
}

For printf, a double argument is passed as a floating-point value, and %f is the correct specifier. If you use scanf instead, you must remember to use %lf when reading into a double.

#include <stdio.h>

int main(void) {
    double value;
    scanf("%lf", &value);
    printf("You entered: %.2f
", value);
    return 0;
}

That %lf detail matters because scanf needs to know the destination type through the address you pass in.

When to use double

Use double when you need practical decimal precision for calculations that are not exact integers.

Common examples include:

  • Physics or engineering formulas
  • Financial estimates and ratios, when exact decimal representation is not required
  • Statistical averages
  • Geometry and geometry-related measurements
  • Sensor readings and simulation data

Use a different type if your data has different requirements:

  • Use int for counts, indexes, and exact whole numbers.
  • Use fixed-point or decimal libraries if you need exact financial arithmetic.
  • Use float only when memory pressure is more important than precision.

A good mental model: double is approximate

The biggest concept to understand is that double does not store most decimal fractions exactly. It stores a binary approximation. That means values you type and values C stores may not match exactly at the bit level.

For example:

#include <stdio.h>

int main(void) {
    double x = 0.1;
    double y = 0.2;
    double sum = x + y;

    printf("%.17f
", sum);
    return 0;
}

You may see a result that looks slightly surprising if you print enough digits. That is normal. The problem is not that C is broken. The problem is that binary floating-point cannot represent every decimal fraction exactly.

The practical response is simple: treat double as approximate and compare it carefully.

Comparing double values safely

Do not compare floating-point values with == unless you have a very specific reason and fully understand the risk.

Instead, compare the difference against a small tolerance, often called an epsilon.

#include <stdio.h>
#include <math.h>

int main(void) {
    double a = 0.1 + 0.2;
    double b = 0.3;
    double epsilon = 1e-9;

    if (fabs(a - b) < epsilon) {
        printf("Values are close enough.
");
    } else {
        printf("Values differ too much.
");
    }

    return 0;
}

Use a tolerance that makes sense for the scale of your values. A tiny epsilon may be too strict for large numbers, while a loose epsilon may hide real mistakes.

Comparison rules that work in practice

  • Use fabs(a - b) < epsilon for simple equality checks.
  • Choose epsilon based on the problem domain.
  • Be careful when values can be extremely large or extremely small.
  • Avoid chaining many floating-point operations if exactness is essential.

Common mistakes with double

A few recurring errors show up in beginner code. Avoiding them will save time.

1. Using the wrong scanf format

If you read a double, use %lf, not %f.

double value;
scanf("%lf", &value);

2. Comparing with ==

This often fails because of tiny representation differences.

if (value == 0.3) {
    /* risky */
}

3. Forgetting that integer division is different

If both operands are integers, C performs integer division before any conversion.

double x = 5 / 2;   // becomes 2, then stored as 2.0

Write at least one operand as floating-point when you want decimal division.

double x = 5.0 / 2;

4. Relying on default formatting

printf("%f", value) may not show enough digits for debugging. Use more precision when inspecting numeric behavior.

printf("%.17f
", value);

5. Expecting exact decimal money math

If the task is accounting-grade currency arithmetic, double is often not the right tool. Use integer cents or a decimal library instead.

A practical example: averaging numbers

Suppose you want to calculate the average of several measurements.

#include <stdio.h>

int main(void) {
    double values[] = {12.4, 13.1, 11.8, 12.9};
    int count = 4;
    double sum = 0.0;

    for (int i = 0; i < count; i++) {
        sum += values[i];
    }

    double average = sum / count;
    printf("Average: %.2f
", average);
    return 0;
}

This example shows why double is useful. The values are not whole numbers, and the result should preserve decimal detail. The code is simple, but it still relies on the floating-point type behaving consistently across the calculation.

Best practices for working with double

Use these habits to keep your code predictable:

  • Initialize variables before using them.
  • Keep formatting and numeric logic separate.
  • Print more precision while debugging and less precision in final output.
  • Use tolerance-based comparisons for equality checks.
  • Prefer double by default unless memory or hardware constraints say otherwise.
  • Document assumptions when a result is expected to be approximate.

Quick reference

TaskRecommended approach
Declare a decimal variabledouble value = 1.25;
Read from inputscanf("%lf", &value);
Print with 2 decimalsprintf("%.2f", value);
Compare two valuesfabs(a - b) < epsilon
Use exact whole numbersint instead of double

Bottom line

double is the standard floating-point type you will use most often in C when you need decimal math with good precision. It is easy to declare and easy to print, but the real skill is understanding its limitations. Treat it as an approximate numeric type, use scanf and printf correctly, and compare values with tolerance instead of exact equality.

Once you understand those rules, double becomes a reliable tool rather than a source of confusion.

Written by

c-double.com Editorial Team

Editorial team

c-double.com publishes practical how-to guides and educational articles with clear steps and useful context.