Two decimal places using printf( )

C++CPrintfDecimal

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

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.

Solution 3 - C++

For %d part refer to this https://stackoverflow.com/questions/2377733/how-does-this-program-work and for decimal places use %.2f

Solution 4 - C++

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 type cast it to double before printing it using %f like this:

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

My 2 cents :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaaliView Question on Stackoverflow
Solution 1 - C++badgerrView Answer on Stackoverflow
Solution 2 - C++Jonathan LefflerView Answer on Stackoverflow
Solution 3 - C++RozuurView Answer on Stackoverflow
Solution 4 - C++Mike MaskeView Answer on Stackoverflow