To define 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 decimals to be written. Everything written down follows the decimals previously defined:
double num = 2.6534;
cout << num; // 2.7
Check it out at Ideone
If you want to write more numbers just do it cout
directly because the precision has already been defined.
It is important to mention that you additionally need to include the header <iomanip>
:
#include <iomanip>
Note also that the result is not 2,6
as I mentioned and yes 2,7
because it works as if it were rounded. If you want to truncate you have to do it manually at the expense of existing functions in <cmath>
as the function floor
.
Just one more recommendation, avoid using using namespace std
. I kept to agree with your question, however this may 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
Enter a minimum code, complete or verifiable, https://answall.com/help/mcve
– Sveen