Two decimal places using printf ()

I am trying to write a number up 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 this?

Thank.

+45
c ++ c decimal printf
Jan 24 '11 at 16:23
source share
4 answers

You want %.2f , not 2%f .

Alternatively, you can replace %d with %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 complete description of the printf formatting options: printf

+95
Jan 24 '11 at 16:26
source share

Use "%.2f" or options.

See the POSIX specification for a valid specification of printf() format strings. Note that it separates the additional POSIX features from the basic C99 specification. There are several C ++ sites that appear on Google search, but some at least have a dubious reputation, judging by the comments that can be found elsewhere on SO.

Since you are coding in C ++, you should probably avoid printf() and its relatives.

+6
Jan 24 '11 at 16:25
source share

In the %d section, refer to this. How does this program work? , and for decimals use %.2f

+4
Jan 24 '11 at 16:29
source share

Try using a format like% d.% 02d

 int iAmount = 10050; printf("The number with fake decimal point is %d.%02d", iAmount/100, iAmount%100); 

Another approach is to print it twice before printing it using% f, like this:

 printf("The number with fake decimal point is %0.2f", (double)(iAmount)/100); 

My 2 cents :)

-2
Jul 30 '11 at 17:40
source share



All Articles