SETPRECISION()

This C++ manipulator is used to control the number of significant digits or decimal places displayed when outputting floating-point numbers with streams like std::cout. By default, setprecision(n) sets the total number of significant digits shown. However, when used in combination with the fixed manipulator, it sets the number of digits after the decimal point instead. This function is particularly useful for formatting monetary values, measurements, or scientific data where precision is important. It does not affect the actual value stored in memory—only how it's displayed during output.

std::ios_base& setprecision(int n);

METHOD 1: WITHOUT THE "FIXED" MANIPULATOR

#include <iostream>
#include <iomanip>  // for setprecision

using namespace std;

int main() {
    float temp = 36.6789123f;
    double distance = 384400.123456789;

    cout << "Temperature (float): " << setprecision(8) << temp << endl;
    cout << "Distance (double): " << setprecision(15) << distance << endl;

    return 0;
}

 * when using the setprecision() function, the TOTAL digit output must be 
   considered - both before and after the decimal point if NOT using the "fixed"
   manipulator
    - std::setprecision(n) means n significant digits total

METHOD 2: WITH THE "FIXED" MANIPULATOR

#include <iostream>
#include <iomanip>  // for setprecision

using namespace std;

int main() {
    float temp = 36.6789123f;
    double distance = 384400.123456789;

    cout << "Temperature (float): " << fixed << setprecision(1) << temp << endl;
    cout << "Distance (double): " << fixed << setprecision(4) << distance << endl;

    return 0;
}

 * std::fixed + setprecision(n)	means n digits after the decimal point

ALTERNATE METHOD: VIA C FUNCTIONS

#include <iostream>
#include <cstdio>      //for c printf() instead of using iomapip setprecision()
using namespace std;

int main(int argc, char *argv[])
{
  float temp = 36.6789123f
  double distance = 384400.123456789;
  
  printf("Temperature (float): %f\n", temp);
  printf("Distance (double): %lf\n", distance);
  
  return 0;
}

Last updated