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:
#include <iostream>
and#include <iomanip>
: These are header files included for input/output stream and input/output manipulation in C++.int main() { }
: This is the main function where the program execution begins and contains the code to be executed.double number = 123.456789;
: A double variable namednumber
is declared and initialized with the value123.456789
.std::cout << std::fixed << std::setprecision(2) << number << std::endl;
:std::cout
: Standard output stream used to print data.std::fixed
: Sets the floating-point numeric output to be in fixed-point notation.std::setprecision(2)
: Sets the precision of floating-point output to 2 digits after the decimal point.number
: The variable to be printed with the specified precision.std::endl
: Outputs a newline character to end the line and flush the output buffer.return 0;
: Indicates successful completion of themain()
function and returns 0 to the operating system, indicating successful program execution.