Why does printf print a strange number when I use %d for a float?

November 14, 2026 4 answers
Asked by 4z~paperweight_629

I have a float containing a Fahrenheit temperature, but printf with %d prints a strange integer. I know %f fixes it, but why doesn't %d just drop the decimal part?

Answers

r61+pktmux_804

%d tells printf to expect an int. It doesn't ask printf to convert whatever argument you passed into an int. In a variadic call like printf, a float argument is promoted to double, so the actual argument and the expected type don't match.

That mismatch causes undefined behavior. You might see a different value between runs, the same odd value, or something else entirely. Use printf("%f", fahrenheit) for the floating point value, or printf("%.2f", fahrenheit) to show two digits after the decimal point.

4z~paperweight_629:

What if I actually want 68 rather than 68.9?

6r~lunchbox_735:

Use printf("%d", (int)fahrenheit). The cast converts the value to int, truncating toward zero, as long as the result is representable as an int.

Reply to this answer
Nerwick.5t

The hardware details depend on the calling convention. On some systems, floating point and integer arguments are passed in different registers. When the format says %d, printf may look for an integer somewhere other than where the double was passed.

So it isn't necessarily reading the float's bits as an integer. That's one possible mental picture on some systems, but it doesn't explain every result and the language doesn't guarantee any particular behavior here.

Reply to this answer
f206+txdecode_4

The temperature calculation is fine as written: (celsius * 9 / 5) + 32. Multiplication and division associate left to right, so celsius * 9 is floating point, and the division is too.

Watch out if you rewrite it as celsius * (9 / 5), though. Both operands inside those parentheses are integers, so 9 / 5 is 1. Writing 9.0f / 5.0f avoids that integer division.

Reply to this answer
Moxren-9c

Turn on compiler warnings for format strings. For example, GCC and Clang can flag this mismatch with -Wall -Wextra. That catches the problem before you have to puzzle over whatever number happens to appear.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions