How can you control the decimal output in C++ using std::fixed and std::setprecision()?

0448

In C++, you can control the decimal output using std::fixed and std::setprecision() from the <iomanip> header. std::fixed ensures that the output is in fixed-point notation, while std::setprecision() sets the number of digits to be displayed after the decimal point.

Here’s an example:

#include <iostream>
#include <iomanip> // Include for std::setprecision

using namespace std;

int main() {
    double number = 123.456789;

    // Output with fixed decimal points
    cout << fixed << setprecision(2) << number << endl; // Outputs: 123.46
    cout << fixed << setprecision(4) << number << endl; // Outputs: 123.4568

    return 0;
}

In this example:

  • std::fixed ensures that the number is displayed in fixed-point notation.
  • std::setprecision(2) sets the output to show 2 decimal places.
  • std::setprecision(4) sets the output to show 4 decimal places.

0 Comments

no data
Be the first to share your comment!