Course contentsShow
← C
Lesson 99 of 1,2192. Variables and TypesFree lesson

The `long double` type

The long double type

What you'll learn: How to use the most precise floating-point type in C for calculations that require extreme accuracy.

Precision Beyond the Standard

When you think of decimal numbers in C, float and double are the usual suspects. A float is like a standard ruler, good for general measurements. A double is like a high-end caliper, offering twice the precision. But what if you are calculating the trajectory of a spacecraft or the microscopic fluctuations of an atomic clock?

That is where the long double comes in. It is the "heavy-duty" version of a floating-point number. While a double usually occupies 8 bytes of memory, a long double often uses 12 or 16 bytes (depending on your computer’s architecture), allowing it to store many more digits after the decimal point with significantly less rounding error.

Working with Long Doubles

To use a long double, you need to pay attention to two specific details: the suffix and the format specifier.

When you write a decimal number in your code, C assumes it is a regular double. To tell the compiler "this is a long double," you must add an L to the end of the number. Similarly, when printing the value using printf, you use the %Lf specifier (the capital 'L' is critical).

#include <stdio.h>

int main() {
    // A regular double
    double pi = 3.141592653589793;

    // A long double with the 'L' suffix
    long double precisePi = 3.141592653589793238462643383279L;

    printf("Standard Double: %.15f\n", pi);
    printf("Long Double:     %.25Lf\n", precisePi);

    return 0;
}

The Trade-off

Think of long double like a high-resolution 8K video file. It captures incredible detail, but it takes up more storage space and requires more processing power to move around. Because these numbers are so large, your computer might perform math slightly slower with them compared to a standard float.

In most everyday programming, a double is more than enough. However, when you reach the limits of standard precision, long double is your safety net for keeping your calculations as close to reality as possible.

Key takeaway

Use long double for maximum decimal precision by appending an L to literals and using the %Lf specifier for input and output.