To achieve high-precision floating-point output in C, especially beyond standard double precision, it's essential to understand format specifiers, data types, and compiler-specific behaviors. The following examples demonstrate how to correctly print extended-precision values using long double and appropriate format strings.
Environment Considerations
Certain environments like Cygwin64 with GCC support higher precision for long double (typically 80-bit extended precision), whereas MinGW64 may not provide the same level of accuracy due to differences in runtime library implementations.
Basic Example: Printing High-Precision Values
#include <stdio.h>
#include <math.h>
int main(void) {
// Print cosine with 19 decimal places
printf("%.19f\n", cos(3.1415926 / 3));
// Literal interpreted as double (limited precision)
printf("%.49f\n", 1.3456789123456789123456789123456789123456789123456789);
// Explicit long double literal
long double val = 1.3456789123456789123456789123456789123456789123456789L;
printf("%.49Lf\n", val);
return 0;
}
Sample Output:
0.5000000154700405819
1.3456789123456789347699213976738974452018740000000
1.3456789123456789123269364272239556612476010000000
Note that regular double literals cannot retain more than ~17 significant decimal digits. Only long double literals (with L suffix) and proper %Lf formatting can expose extended precision.
Format Specifier Behavior
Mixing format specifiers and types leads to undefined behavior or incorrect output:
%f,%lf: Fordouble(they are equivalent inprintf)%Lf: Required forlong double%llf: Invalid — not a standard specifier and often treated as%lfor causes garbage output
Common Pitfalls and Corrections
The following corrected example shows proper usage:
#include <stdio.h>
int main(void) {
long double ld = 1.23L;
double d = 1.3456789123;
printf("ld via %%Lf: %.15Lf\n", ld);
printf("d via %%f: %.15f\n", d);
// Correctly cast and print long double
long double ld2 = 1.3456789123L;
printf("ld2 via %%Lf: %.15Lf\n", ld2);
// Size verification
printf("Sizes: long double=%zu, double=%zu\n",
sizeof(long double), sizeof(double));
return 0;
}
Key Observations:
- Always include
<stdio.h>to avoid implicit function declaration warnings. - Use
Lsuffix forlong doubleliterals. - Only
%Lfreliably printslong doublevalues with full precision. - On Cygwin64/gcc,
long doubleis typically 16 bytes (80-bit extended precision), offering ~19–21 decimal digits of precision.