• Home
  • 2.9 Formatting Floating Point Values

2.9 Formatting Floating Point Values

View Categories

2.9 Formatting Floating Point Values

1 min read

Table of Contents

By default, floating-point values are displayed using a format chosen by the output stream. C++ provides stream manipulators that allow the number of digits after the decimal point and the display format to be controlled.

The <iomanip> library provides manipulators such as std::fixed, std::scientific, and std::setprecision() for formatting floating-point output.

Source Code #

#include <iostream>
#include <iomanip>

int main()
{
    double value = 123.456789;

    std::cout << "Default     : " << value << '\n';
    std::cout << "Fixed       : "
              << std::fixed << std::setprecision(2)
              << value << '\n';

    std::cout << "Scientific  : "
              << std::scientific << std::setprecision(3)
              << value << '\n';

    return 0;
}

Output #

Default     : 123.457
Fixed       : 123.46
Scientific  : 1.235e+02

Explanation #

  • #include <iomanip> includes the header that provides stream manipulators for formatting output.
  • std::fixed displays floating-point values using fixed-point notation.
  • std::scientific displays floating-point values using scientific notation.
  • std::setprecision() specifies the number of digits displayed.
  • When used with std::fixed, std::setprecision() specifies the number of digits after the decimal point.
  • When used with std::scientific, std::setprecision() specifies the number of digits after the decimal point in scientific notation.
  • Formatting manipulators affect subsequent floating-point output until another formatting manipulator changes the stream state.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *