Two decimal places using printf( )

aali picture aali · Jan 24, 2011 · Viewed 214.1k times · Source

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.

Answer

badgerr picture badgerr · Jan 24, 2011

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