C++ float and double Using setprecision() For Floating-Point Numbers

C++ provides the setprecision() function from the header to control the precision of floating-point numbers when they are printed. The setprecision() function takes an integer argument that represents the number of digits to be displayed after the decimal point.

To use setprecision() in C++, follow these steps:

  1. Include the header file at the beginning of your program to access the setprecision() function.

  2. Declare the floating-point number you want to format, such as float or double.

  3. Use the cout object to display the floating-point number.

  4. Call the setprecision() function before outputting the floating-point number using the << operator.

  5. 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.

  6. 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 and headers. We declare a double variable named "number" and assign it the value of pi (approximately). Then, we use std::cout to display the value of "number" with a precision of 4 digits after the decimal point. The output of this program would be "3.142".

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.