print float up to 3 decimal places in c++
To print a float up to 3 decimal places in C++, you can use the std::cout
stream and the std::setprecision
manipulator from the <iomanip>
library. Here are the steps:
- Include the
<iostream>
and<iomanip>
libraries at the beginning of your program:
#include <iostream>
#include <iomanip>
- Declare your float variable and assign a value to it:
float myFloat = 3.14159;
- Use the
std::cout
stream to output the float value, and set the precision usingstd::setprecision(3)
:
std::cout << std::setprecision(3) << myFloat << std::endl;
This will print the float value up to 3 decimal places. The std::setprecision(3)
manipulator sets the precision of the floating-point output to 3 decimal places. The std::cout
stream is used to output the float value, and std::endl
is used to insert a newline character after printing.
Here's the complete code:
#include <iostream>
#include <iomanip>
int main() {
float myFloat = 3.14159;
std::cout << std::setprecision(3) << myFloat << std::endl;
return 0;
}
When you run this code, it will output:
3.14
Note that the output is rounded to 3 decimal places. If you want to truncate the float value instead of rounding, you can use the std::fixed
manipulator along with std::setprecision(3)
:
std::cout << std::fixed << std::setprecision(3) << myFloat << std::endl;
This will output:
3.141
I hope this helps! Let me know if you have any further questions.