94

I'm trying to write a number to two decimal places using printf() as follows:

#include <cstdio>
int main()
{
  printf("When this number: %d is assigned to 2 dp, it will be: 2%f ", 94.9456, 94.9456);
  return 0;
}

When I run the program, I get the following output:

# ./printf
When this number: -1243822529 is assigned to 2 db, it will be: 2-0.000000

Why is that?

Thanks.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • 2
    the -1234... part is the representation of your 32 bit floating point as an integer. The second part is wrong you should have %2.2f, but still I can't explain the -0.0000... part. I for one get a correct result except that running your code puts an extra 2 in front of the float. –  Jan 24 '11 at 16:30
  • 1
    @nvm: The zeroes appear because 94.9456 was pushed onto the stack as a double (8 bytes), and the %d processed the first 4 bytes as an integer, and the next 4 bytes were zeroes, and the code then read those 4 trailing bytes from the first number plus the leading 4 bytes of the second float and tried to treat it as a double. The answer was so small that the fixed-point format treats it as zero. And this was run on an Intel chip, not a RISC machine. – Jonathan Leffler Jan 24 '11 at 17:01
  • Seems that putting an integer before "f" like that "%10f" does not have any effec, as it is just like writing "%f"? I tried that and just get the result as if it where "%f". –  Jan 24 '11 at 17:13

3 Answers3

177

What you want is %.2f, not 2%f.

Also, you might want to replace your %d with a %f ;)

#include <cstdio>
int main()
{
printf("When this number: %f is assigned to 2 dp, it will be: %.2f ", 94.9456, 94.9456);
return 0;
}

This will output:

When this number: 94.945600 is assigned to 2 dp, it will be: 94.95

See here for a full description of the printf formatting options: printf

Jason
  • 542
  • 5
  • 24
badgerr
  • 7,802
  • 2
  • 28
  • 43
7

Use: "%.2f" or variations on that.

See the POSIX spec for an authoritative specification of the printf() format strings. Note that it separates POSIX extras from the core C99 specification. There are some C++ sites which show up in a Google search, but some at least have a dubious reputation, judging from comments seen elsewhere on SO.

Since you're coding in C++, you should probably be avoiding printf() and its relatives.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
5

For %d part refer to this How does this program work? and for decimal places use %.2f

Community
  • 1
  • 1
Rozuur
  • 4,115
  • 25
  • 31