What is the purpose of the setprecision() used in this C++ program?

225 views Asked by At

This example program was created with the sole purpose of showing what setprecision and setw does. I dont understand the purpose of the third line that says "setprecision(5)". I commented the line out to see the difference but it looks the exact same. Is there no purpose?

 cout << "\nSales Figures\n";
 cout << "-------------\n";
 cout << setprecision(5);
 cout << "Day 1: " << setw(8) << day1 << endl;
 cout << "Day 2: " << setw(8) << day2 << endl;
 cout << "Day 3: " << setw(8) << day3 << endl;
 cout << "Total: " << setw(8) << total << endl;
1

There are 1 answers

0
Ethan N On

The setprecision() function is part of the "iomanip" library and is used when you need to output a float to a certain number of decimal places. This is good for displaying money amounts and other things that typically are shown with a set number of digits after the decimal point (even if those digits are 0).

Say you have a float called price: If you stored 10.0 in that float, C++ would not know how many decimal points to output when you print into the screen; setprecision(2) would make the output 10.00.

You can find the documentation at this link: https://cplusplus.com/reference/iomanip/setprecision/.

It includes the following code as an example of how setprecision() works.

// setprecision example
#include <iostream>     // std::cout, std::fixed
#include <iomanip>      // std::setprecision

int main () {
  double f =3.14159;
  std::cout << std::setprecision(5) << f << '\n'; // This outputs 3.1415
  std::cout << std::setprecision(9) << f << '\n'; // This outputs 3.14159
  std::cout << std::fixed; 
  std::cout << std::setprecision(5) << f << '\n'; // This outputs 3.14159
  std::cout << std::setprecision(9) << f << '\n'; // This outputs 3.141590000
  return 0;
}

Note that setprecision() is only applicable to data types with decimal points such as floats and doubles.