how to fixed how many digit will be after point in c++
You can use the setprecision()
function from the <iomanip>
header in C++ to fix the number of digits after the decimal point. Here's an example:
#include <iostream>
#include <iomanip>
int main() {
double num = 3.1415926535;
int precision = 4; // Change this value to set the desired precision
std::cout << std::fixed << std::setprecision(precision) << num << std::endl;
return 0;
}
Explanation:
1. #include <iostream>
and #include <iomanip>
: Includes necessary libraries for input/output and manipulators.
2. double num = 3.1415926535;
: Declares a variable num
of type double
and initializes it with a value.
3. int precision = 4;
: Defines the precision value. Change this variable to set the desired number of digits after the decimal point.
4. std::cout << std::fixed << std::setprecision(precision) << num << std::endl;
: Prints the value of num
with fixed precision using std::setprecision(precision)
. The std::fixed
manipulator ensures that the number is displayed in fixed-point notation.
5. return 0;
: Indicates the successful completion of the main()
function.
Replace the num
variable with the number you want to format and adjust the precision
variable to specify the number of digits after the decimal point that you need for your output.