I'm working on a small program that outputs a cash quantity. I'd like for it to show 2 decimals at the end no matter if there are values present so that ten cents is displayed as 0.10 rather than 0.1. The problem is that whenever I end up doing printf("%0.3f", d);
it prints out as 0.1. Is there any way to fix this or is that just how C is?
Asked
Active
Viewed 155 times
-1
-
5Hot tip: don't use floating point numbers to represent currency. – Carl Norum Sep 20 '19 at 22:29
-
5`%.2f` should do what you want. – Barmar Sep 20 '19 at 22:30
-
When I use `%0.3f` I get `0.100`, not `0.1`. – Barmar Sep 20 '19 at 22:42
1 Answers
2
Linux systems have pretty good documentation on the C standard library, written in the form of man pages. Man pages are also available on the Internet. In your case, you'd want to check out fprintf(3)
:
https://linux.die.net/man/3/fprintf
http://man7.org/linux/man-pages/man3/fprintf.3p.html
The precision governs the number of digits after the decimal-point character when performing a %f
conversion. In your case, the precision would most likely be .2 rather than .3.
Please notice that the %g
conversion understands precisions in a different way.
The man page also reminds you of the necessary #include<stdio.h>
directive. It would also tell you to link your program against a specific library if that were necessary.

Vicky
- 969
- 1
- 11
- 19
-
Neither here nor there, but I've always preferred the [man7.org](http://man7.org/index.html) pages. You can help the quality of your answer by explaining (briefly) the use of the optional *precision* within the format string (as applied to floating-point types). That will help take your answer from what is essentially a comment to an actual answer -- that with a bit more effort may be worthy of an upvote. – David C. Rankin Sep 20 '19 at 23:23
-
Thanks for your input, I've expanded my answer. (I'm not a huge fan of die.net either, their variable-width font is kind of ugly.) – Vicky Sep 20 '19 at 23:45
-
Welcome to StackOverflow. That little bit of effort goes a long way. Remember, when you answer, you step into the role of teacher, and we all remember those teachers that what would just hand you the book and say "It's in here...." -- we try not to be one of those `:)` – David C. Rankin Sep 20 '19 at 23:48
-
True, too many teachers like that are out there already... thanks for your suggestion! – Vicky Sep 20 '19 at 23:58