How to print up to 2 decimal places in c++ code example

Example 1: how to print a decimal number upto 6 places of decimal in c++

#include <iostream>
#include <iomanip>

int main()
{
    double d = 122.345;

    std::cout << std::fixed;
    std::cout << std::setprecision(2);
    std::cout << d;
}

Example 2: round double to 2 decimal places c++

double d = 0.12345;
std::cout.precision(2); // for accuracy to 2 decimal places 
std::cout << d << std::endl; // 0.12

Example 3: how to format decimal palces in c++

std::cout << std::setprecision(2) << std::fixed;
// where the 2 is how many decimal places you want
// note you need to <iomanip>

Tags:

Cpp Example