Printing floating point numbers code snippet

Summary

Source code of C++ program, demonstrating how to print floating point numbers in various formats.

Source code

C++: print_floating_point_numbers.cpp

#include <iostream>

#include <iomanip>

 

using namespace std;

 

int main() {

      double pi = 3.141592653;

 

      // print 3.14

      cout.precision(2);

      cout << "Two digits after point: " << fixed << pi << endl;

 

      // print pi using scientific notation

      cout << "Scientific notation: " << scientific << pi << endl;

 

      // set default notation

      cout.unsetf(ios_base::scientific);

 

      // set enough precision to show all digits

      // (requires <iomanip>)

      cout << "PI: " << setprecision(10) << pi << endl;

 

      return 0;

}

 

Sample run

C/C++

Two digits after point: 3.14
Scientific notation: 3.14e+000
PI: 3.141592653