Skip to content

Instantly share code, notes, and snippets.

@kayceesrk
Created August 21, 2025 09:51
Show Gist options
  • Save kayceesrk/4f454ced2e1b9a1d55270f036520829a to your computer and use it in GitHub Desktop.
Save kayceesrk/4f454ced2e1b9a1d55270f036520829a to your computer and use it in GitHub Desktop.

๐Ÿงฎ Why Does C Print 0.300000 for 0.1 + 0.2?

This short example shows how floating-point numbers behave in C and why simple expressions like 0.1 + 0.2 don't always behave as you'd expect.


๐Ÿ”ข Code: test.c

#include <stdio.h>

int main () {
    printf("%f\n", 0.1 + 0.2);        // Default format: 6 digits after decimal
    printf("%.17f\n", 0.1 + 0.2);     // Full precision for a double
}

๐Ÿ’ป Output

0.300000
0.30000000000000004

๐Ÿง  What's Going On?

Floating-point numbers are approximations

C uses the IEEE 754 standard to represent floating-point numbers (float, double).

  • Some numbers like 0.5 are exact in binary.
  • But others like 0.1 or 0.2 cannot be exactly represented.

So when you write:

0.1 + 0.2

You're actually adding:

0.10000000000000000555... + 0.20000000000000001110...

Which gives:

0.30000000000000004441...

This is not exactly 0.3, though it's very close.


๐Ÿ–จ๏ธ Why the different outputs?

By default, printf("%f", ...) prints only 6 digits after the decimal

Format String Meaning Output
%f 6 digits (default) 0.300000
%.17f 17 digits = full double 0.30000000000000004

The value 0.30000000000000004 is rounded to 0.300000 when printed with %f.


๐Ÿ“Œ Takeaway for Students

  • Floating-point numbers are not exact.
  • Even simple decimal values like 0.1 and 0.2 can have invisible errors due to binary representation.
  • C (and most other languages) hides this by default, but you can reveal it using higher precision formats.
  • Always be careful when comparing floats or expecting exact decimal values in output.

โœ… This is expected behavior, not a bug!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment