how print fload wiht 2 decimal in c++
To print a float with two decimal places in C++, you can make use of the std::setprecision
manipulator from the <iomanip>
header. Here are the steps to achieve this:
- Include the
<iostream>
and<iomanip>
headers in your code to use the necessary input/output and manipulator functions:
#include <iostream>
#include <iomanip>
- Declare a float variable and assign it the desired value:
float number = 3.14159;
- Use the
std::fixed
andstd::setprecision
manipulators to format the float with two decimal places. Thestd::fixed
manipulator ensures that the number is printed in fixed-point notation:
std::cout << std::fixed << std::setprecision(2) << number << std::endl;
- Run the code, and the float value will be printed with two decimal places:
3.14
Here's the complete code example:
#include <iostream>
#include <iomanip>
int main() {
float number = 3.14159;
std::cout << std::fixed << std::setprecision(2) << number << std::endl;
return 0;
}
This code will output 3.14
, which is the float value 3.14159
rounded to two decimal places.