set precision on floating numbers
#include <iostream>
#include <iomanip>
int main() {
double number = 3.14159;
// Set precision to 3 decimal places
std::cout << std::fixed << std::setprecision(3) << number << std::endl;
return 0;
}
Explanation:
#include <iostream>
: Includes the input/output stream for handling input and output operations.#include <iomanip>
: Includes the input/output manipulator for controlling output formatting.double number = 3.14159;
: Declares a double variable namednumber
and assigns the value3.14159
.std::cout << std::fixed << std::setprecision(3) << number << std::endl;
: Prints the value ofnumber
to the standard output (std::cout
) with a precision of 3 decimal places.std::fixed
ensures that floating-point numbers are displayed in fixed-point notation.std::setprecision(3)
: Sets the precision of floating-point output to 3 decimal places.
This code will output 3.142
, rounding the original number 3.14159
to three decimal places.