Home >Backend Development >C++ >How Can I Control Decimal Precision When Outputting Floating-Point Numbers in C ?

How Can I Control Decimal Precision When Outputting Floating-Point Numbers in C ?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-04 15:41:41533browse

How Can I Control Decimal Precision When Outputting Floating-Point Numbers in C  ?

Preserving Decimal Precision with cout

In this scenario, where we aim to output specific floating-point values while maintaining a constant decimal place count, the setprecision manipulator from the header emerges as an invaluable tool.

To achieve this desired formatting, consider the following steps:

  1. Include both the and headers.
  2. Utilize the std::fixed specifier to indicate that you prefer non-scientific notation.
  3. Employ std::setprecision(value), setting the specified value to represent the number of desired decimal places.
  4. Output your floating-point value.

For instance, consider the following code snippet:

#include <iostream>
#include <iomanip>

int main()
{
    double d = 122.345;

    std::cout << std::fixed;
    std::cout << std::setprecision(2);
    std::cout << d;
}

This code, when executed, will produce the desired output:

122.34

The above is the detailed content of How Can I Control Decimal Precision When Outputting Floating-Point Numbers in C ?. 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