Two decimal places using printf( ) Two decimal places using printf( ) c c

Two decimal places using printf( )


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


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.


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