Home >Backend Development >C++ >How Can I Accurately Print Decimal Values to a Specific Precision in C ?
Printing Decimal Values Accurately with C Streams
When working with floating-point numbers in C , it's often necessary to control the number of decimal places displayed during output. By default, the standard output operator cout may not format numbers to the desired precision.
Solution Using
To specify the number of decimal places for floating-point output, use the std::fixed and std::setprecision manipulators from the
#include <iomanip> std::cout << std::fixed; std::cout << std::setprecision(2); std::cout << d;
std::fixed sets the floating-point representation to fixed-point notation, and std::setprecision(2) specifies that two decimal places will be displayed.
Example Usage
Consider the following example:
double d = 122.345; std::cout << std::fixed; std::cout << std::setprecision(2); std::cout << d;
This code will output:
122.34
Additional Notes:
The above is the detailed content of How Can I Accurately Print Decimal Values to a Specific Precision in C ?. For more information, please follow other related articles on the PHP Chinese website!