get number round off to two decimal places c++
To round off a number to two decimal places in C++, you can use the std::setprecision
function from the <iomanip>
library. Here are the steps to do it:
- Include the necessary libraries:
#include <iostream>
#include <iomanip>
- Declare the number that you want to round off:
double number = 3.14159;
- Set the precision to two decimal places using the
std::setprecision
function:
std::cout << std::fixed << std::setprecision(2);
The std::fixed
manipulator ensures that the number is displayed with a fixed number of decimal places.
- Print the rounded number:
std::cout << "Rounded number: " << number << std::endl;
Here's the complete code:
#include <iostream>
#include <iomanip>
int main() {
double number = 3.14159;
std::cout << std::fixed << std::setprecision(2);
std::cout << "Rounded number: " << number << std::endl;
return 0;
}
When you run this code, the output will be:
Rounded number: 3.14
This code sets the precision for the output stream, ensuring that the number is rounded off to two decimal places when it is printed.