Course contentsShow
← C
Lesson 908 of 1,21912. The Standard LibraryFree lesson

Checking `FLT_DIG` and `DBL_DIG` for precision limits

Checking FLT_DIG and DBL_DIG for precision limits

What you'll learn: How to use the <float.h> header to determine exactly how many decimal digits your float and double variables can reliably hold.

The "Blurry" Edge of Numbers

In C, floating-point numbers are not infinite. Imagine trying to write a long number like PI on a small sticky note. Eventually, you run out of paper, and you have to stop writing digits. Computers have a similar physical limit.

Because computers store numbers in binary (base-2), they can't always represent decimal (base-10) fractions perfectly. After a certain number of digits, the value becomes "blurry" or slightly inaccurate. The constants FLT_DIG and DBL_DIG tell you exactly where that blurriness begins.

Meet the Constants

To find these limits, we use the <float.h> header file.

  • FLT_DIG: The number of decimal digits of precision for a float. (Usually 6).
  • DBL_DIG: The number of decimal digits of precision for a double. (Usually 15).

Think of these numbers as a "guarantee." If FLT_DIG is 6, the C standard promises that any 6-digit decimal number can be stored and brought back without losing its value. If you try to store 10 digits in a float, the computer will "guess" the last 4, leading to strange math errors.

Seeing Limits in Action

Here is how you check these limits on your specific machine:

#include <stdio.h>
#include <float.h>

int main() {
    printf("Float precision (FLT_DIG): %d digits\n", FLT_DIG);
    printf("Double precision (DBL_DIG): %d digits\n", DBL_DIG);

    // Example of precision loss
    // A float can only reliably hold about 6-7 digits.
    float my_pi = 3.14159265358979f; 
    
    // Printing to 10 decimal places shows the "blur"
    printf("Stored float: %.10f\n", my_pi);

    return 0;
}

When you run this, you will notice that the float starts to diverge from the actual value of PI after the 6th or 7th digit. It isn't "broken"; it has simply reached its physical capacity.

Why This Matters

When building software for accounting or scientific research, you need to know which tool to use. If your data requires 10 digits of accuracy, a float (guaranteed for 6) will give you wrong answers. By checking DBL_DIG, you confirm that a double (guaranteed for 15) is the safer choice for your project.

Key takeaway

Use FLT_DIG and DBL_DIG from <float.h> to know the maximum number of reliable decimal digits your variables can store before rounding errors occur.