To set the number of decimal places to be written, you must use setprecision
and fixed
:
cout << fixed << setprecision(1);
The number passed in setprecision
indicates the number of decimal places to be written. All that is written from below follows the previously defined decimals:
double num = 2.6534;
cout << num; // 2.7
See it on Ideone
If you want to write more numbers, just cout
directly because the precision has already been defined.
It is important to mention that you must additionally include the header <iomanip>
:
#include <iomanip>
Note also that the result is not 2,6
as you mentioned, but 2,7
because it works as if it were rounded. If you want to truncate you will have to do this manually at the expense of existing functions in <cmath>
such as floor
.
Just one more recommendation, avoid using using namespace std
. I kept to agree with your question, however this can cause you problems with name collisions among other things.
Following this recommendation, therefore without using namespace std
would look like this:
std::cout << std::fixed << std::setprecision(1);
double num = 2.6534;
std::cout << num;
See also this version on Ideone