C++ How to get fixed digit after decimal in output???? Like f=123.456789 I want to show 123.46 in output.
Asked
Active
Viewed 3,044 times
0
-
possible duplicate of [How do I print a double value with full precision using cout?](http://stackoverflow.com/questions/554063/how-do-i-print-a-double-value-with-full-precision-using-cout) – Alexandre Lavoie May 24 '15 at 06:03
-
So you took the `cout` path. You deserve a punishment for this and the punishment will take the form of C++ formatting. You'll suffer this pain for the rest of your C++ programming life. – 6502 May 24 '15 at 06:09
4 Answers
2
You can use the setprecision() method in C++.
cout<<std::fixed<<std::setprecision(2)<<f;

Adithya Upadhya
- 2,239
- 20
- 28
-
I'd downvote the answer given how ugly and wrong this code is on so many levels. I won't just because it is, unfortunately, what C++ texts recommend to do. But I really cannot upvote it, that's too much. – 6502 May 24 '15 at 06:03
0
Another way is to use printf function, make sure that you include stdio.h file to use it,
printf("%0.2f",f);
Here %f is format specifier(float) and 0.2 between '%' and 'f' is used to set precision upto two decimal places.

Angad Singh
- 1,032
- 1
- 17
- 36
-
Well in the title the OP asked using with `cout` and `printf` can't be used with `cout`... – Alexandre Lavoie May 24 '15 at 06:03
0
you could also use boost::format
#include <boost/format.hpp>
cout << boost::format("%.2f") % f << endl;

sp2danny
- 7,488
- 3
- 31
- 53
0
You'd require I/O manipulator for decimal precision.
#include <iomanip>
#include <iostream>
int main( )
{
double foo = 123.456789L;
std::cout << std::setprecision(2) << std::fixed << foo << std::endl;
return 0;
}

Achilles Rasquinha
- 353
- 1
- 3
- 11