Home  >  Article  >  Backend Development  >  How to Achieve Precise Floating-Point Formatting with std::ostream?

How to Achieve Precise Floating-Point Formatting with std::ostream?

Susan Sarandon
Susan SarandonOriginal
2024-10-28 18:03:29945browse

How to Achieve Precise Floating-Point Formatting with std::ostream?

Formatted Output of Floating-Point Values Using std::ostream

Question:

How can I achieve precise control over the formatting of floating-point values using std::ostream, similar to the printf_s function shown below?

<code class="cpp">printf_s("%11.6lf", my_double); // Prints " 42.000000"</code>

Answer:

To format floating-point values with std::cout, utilize stream manipulators. The following code achieves the desired output:

<code class="cpp">std::cout << std::fixed << std::setw(11) << std::setprecision(6) << my_double;</code>

Explanation:

  • std::fixed: Specifies that the value should be formatted with a fixed number of decimal places.
  • std::setw(11): Defines the minimum field width to which the value is padded with spaces.
  • std::setprecision(6): Sets the number of decimal places to be displayed.
  • std::setfill('0'): (Optional) Fills empty spaces with the specified character ('0' in this case).

Additional Resources:

For comprehensive documentation on std::ostream formatting, refer to the following resources:

  • [std::ostream formatting](https://en.cppreference.com/w/cpp/io/manipulators) on cppreference.com
  • [std::ostream](https://www.learncpp.com/cpp-tutorial/formatted-output-with-io-manipulators/) on learncpp.com

The above is the detailed content of How to Achieve Precise Floating-Point Formatting with std::ostream?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn