Possible Duplicate:
Convert a double to fixed decimal point in C++
Suppose , I have double a = 0
and I want to print it as 0.0000
.
I've tried this :
cout.precision(4) ;
cout<<a<<endl ;
but it gaves 0
as the output.
By using the setprecision function, we can get the desired precise value of a floating-point or a double value by providing the exact number of decimal places. If an argument n is passed to the setprecision() function, then it will give n significant digits of the number without losing any information.
You can set the precision directly on std::cout and use the std::fixed format specifier. double d = 3.14159265358979; cout. precision(17); cout << "Pi: " << fixed << d << endl; You can #include <limits> to get the maximum precision of a float or double.
We can print the double value using both %f and %lf format specifier because printf treats both float and double are same. So, we can use both %f and %lf to print a double value.
We can use the printf() and fprintf() function to round numbers to 2 decimal places by providing the %. 2f format specifier.
Just try:
#include <iomanip>
...
cout << fixed << setprecision(4);
cout << a << endl;
See here.
#include <iomanip>
#include <iostream.h>
int main()
{
double a = 0.00;
// print a double, 2 places of precision
cout << setprecision(4) << a << endl;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With