Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print double with precision 4 using cout [duplicate]

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.

like image 800
URL87 Avatar asked Dec 05 '12 16:12

URL87


People also ask

How do you precise a double value in C++?

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.

How do you set up cout precision?

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.

How do you print a double in C++?

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.

How do you do 2 decimal places in C++?

We can use the printf() and fprintf() function to round numbers to 2 decimal places by providing the %. 2f format specifier.


2 Answers

Just try:

#include <iomanip>
...
cout << fixed << setprecision(4);
cout << a << endl;

See here.

like image 79
semekh Avatar answered Oct 22 '22 01:10

semekh


#include <iomanip>
#include <iostream.h>


int main()
{
double a = 0.00;
// print a double, 2 places of precision 
cout << setprecision(4) << a << endl;
}
like image 20
crh225 Avatar answered Oct 21 '22 23:10

crh225