how to print numbers with only 2 digits after decimal point in c++

#include <iostream>
#include <iomanip>

int main() {
    double number = 123.456789;

    std::cout << std::fixed << std::setprecision(2) << number << std::endl;

    return 0;
}

Explanation:

  1. #include <iostream> and #include <iomanip>: These are header files included for input/output stream and input/output manipulation in C++.

  2. int main() { }: This is the main function where the program execution begins and contains the code to be executed.

  3. double number = 123.456789;: A double variable named number is declared and initialized with the value 123.456789.

  4. std::cout << std::fixed << std::setprecision(2) << number << std::endl;:

  5. std::cout: Standard output stream used to print data.
  6. std::fixed: Sets the floating-point numeric output to be in fixed-point notation.
  7. std::setprecision(2): Sets the precision of floating-point output to 2 digits after the decimal point.
  8. number: The variable to be printed with the specified precision.
  9. std::endl: Outputs a newline character to end the line and flush the output buffer.

  10. return 0;: Indicates successful completion of the main() function and returns 0 to the operating system, indicating successful program execution.