C Decimal Precision

C Tutorial

 C Decimal Precision (Beginner → Advanced)

Decimal precision in C language means how many digits are stored and displayed after the decimal point.
This depends on:

  • the data type (float, double, long double)

  • how you print the value (printf format)

  • how floating-point numbers are stored internally (IEEE-754)


 Decimal Precision by Data Type

Data TypeSize (typical)Precision (approx)
float4 bytes~6–7 decimal digits
double8 bytes~15–16 decimal digits
long double10–16 bytes~18+ digits (platform dependent)

float Precision Example


 

Output (approx):

1.123457
  •  Extra digits are lost because float can’t store them accurately.

double Precision Example


 

Output:

1.123456789
  • double preserves more digits.

 Controlling Decimal Places in printf() (Most Important)

Syntax

%.nf

n = number of digits after decimal

Example


 

  • Rounding happens automatically

 Decimal Precision with float vs double


 

Output (approx):

float = 1.23456788
double = 1.23456789
  • Shows precision difference clearly

Why Decimal Precision Is Inexact?

C uses binary floating-point (IEEE-754).
Some decimal numbers cannot be represented exactly in binary.

Famous Example


 

Output:

0.30000000000000004
  • This is normal behavior, not a bug.

 Comparing Floating-Point Numbers

 Wrong Way

if (a == b) { ... }

 Correct Way (Using Tolerance)


 

  • Always compare using a small epsilon

 Decimal Precision in Calculations


 

  •  Integer division happens before assignment
  •  Type casting fixes precision

 Using long double for High Precision


 

  •  Best for scientific & financial calculations

float, double, long double – When to Use?

Use CaseRecommended Type
Memory-critical (embedded)float
General calculationsdouble
High-precision mathlong double
Money (exact values) Floating types (use integers)

 Common Mistakes

  •  Expecting exact decimal values
  •  Comparing floats with ==
  •  Using float for money
  •  Forgetting format precision in printf()

 Interview Questions (Very Important)

  1. Difference between float and double precision?

  2. Why 0.1 + 0.2 != 0.3?

  3. How to print only 2 decimal places?

  4. How to safely compare floating numbers?

  5. When to use long double?


 Summary

  •  Decimal precision depends on data type
  • float ≈ 6 digits, double ≈ 15 digits
  •  Use %.nf to control output precision
  •  Floating numbers are approximate
  •  Never compare floats using ==
  •  Critical for accuracy, interviews & real programs

You may also like...