C++ float and double Using setprecision() For Floating-Point Numbers
C++ provides the setprecision() function from the
To use setprecision() in C++, follow these steps:
Include the
header file at the beginning of your program to access the setprecision() function. Declare the floating-point number you want to format, such as float or double.
Use the cout object to display the floating-point number.
Call the setprecision() function before outputting the floating-point number using the << operator.
Pass the desired precision as an argument to the setprecision() function. This precision specifies the number of digits to be displayed after the decimal point.
Run the program and observe the output with the desired precision.
Here is an example code snippet that demonstrates the usage of setprecision() in C++:
#include <iostream>
#include <iomanip>
int main() {
double number = 3.14159265358979323846;
std::cout << std::setprecision(4) << number << std::endl;
return 0;
}
In this example, we include the
By using setprecision(), you can control the precision of floating-point numbers in C++, ensuring that they are displayed with the desired number of digits after the decimal point.