this is an example of what is happening

consider the program:


#include<iostream.h>

void main(void)
{

double x=2.3767553235;
cout<<x<<endl;

}

when i compile it

the output is only giving 2.37676
Why?

I dont want only 5 decimal places,plz someone tell me why is this happening.

i want it to be say for example 8 or 10 decimal places

thank u so much

so my point is i want 2.3767553235 in the output,why is the pc only putting 2.37676

>> Why?
Why not? It's concievable that there would be a default precision for the stream, one that would be valid everywhere so that it could be portable. It just so happens that that's the case. The default is 6:

#include <iostream>

int main()
{
  double d = 123.4567890123;

  std::cout << "Precision: " << std::cout.precision() << '\n';
  std::cout << "Value: " << d << '\n';
  std::cout.precision(4);
  std::cout << "Value: " << d << '\n';
}

>> i want it to be say for example 8 or 10 decimal places
Assuming your system is capable of holding an accurate precision to 10 digits past the radix including an arbitrary number of digits before the radix, you would do it like this:

#include <iostream>

int main()
{
  double x = 2.3767553235;

  std::cout.precision(11);
  std::cout << x << '\n';
}

However, because the precision is all digits in the number, to get an exact precision of 10 for any whole value, you would need a way to determine the number of digits before the radix. An easy to understand solution is to make a string and take its length:

#include <iostream>
#include <sstream>

namespace jrd {
  int digits(double val)
  {
    std::ostringstream oss;

    oss << static_cast<int>(val);

    return oss.str().length();
  }
}

int main()
{
  double x = 2.3767553235;

  std::cout.precision(10 + jrd::digits(x));
  std::cout << x << '\n';
}

<iostream.h> is not standard, and therefore is becoming increasingly less supported by compilers as standard C++ matures. This isn't a theoretical difference, by the way. My compiler will refuse to compile <iostream.h>.

Another important difference between iostream.h and iostream is that iostream.h has its declarations in the global namespace, while iostream has them in the std namespace.

dogtree's method is quite inefficient. It is possible to directly set the number of decimal places, but you have to make sure the output mode is "fixed" first.

This example produces 10 decimal places.

#include<iostream>

using namespace std;

int main()
{
	double x = 2.3767553235;
	cout << fixed << showpoint << setprecision(10) << x << endl;
}

If you google for "C++ decimal places" you will find this article

http://www.cs.fsu.edu/~myers/c++/notes/basics1.html

and right at the end is a short explanation of formatting decimal numbers.

This article has been dead for over six months. Start a new discussion instead.