views:

108

answers:

2

Hi guys,

I was making a program that rounds up numbers with various decimal places, so as an example 2001.3666 would end up as 2001.37, I managed to make this work by adding 0.005 then times 100 and converted to a int and then divided again by 100.

Everything worked fine, no issues there, was having some fun making some loops too and stuff, but then everything became odd.

you see the first line of then program that repeats what the user typed in begun to display the rounded figure instead of the actual figure the user typed.

after a while I came to the conclusion that it wasn't my code, because I started a new project and quickly made up this code:

#include <iostream>
#include <string> 
using namespace std;


int main()
{
  cout << "enter: ";
  double numberWithDecimalPlaces;
  cin >> numberWithDecimalPlaces;
  cout << "you entered " << numberWithDecimalPlaces << endl;

  system("pause");
  return 0; 
}

I type in 2001.3666 and the program goes to a newline even though I didn't code that in and replies with 2001.37

its exact output is:

enter: 2001.3666
you entered 2001.37

now this is a brand new program in a new project without any of the same variable names as my earlier project and the user input figure is being rounded up, unless cin >> variable is automatically rounding up which i find unlikely it looks like some code from the earlier program is still in memory and conflicting with this code.

which is again unlikely right??

i'm using visual studio 2010 on win7

+3  A: 

Numbers are often rounded when displayed, but you can control how much. Read http://www.cplusplus.com/reference/iostream/manipulators/setprecision/

Ben Voigt
I was under the impression setprecision only truncates the decimal places and does not round up or down. i'm really new to this and I did read about setprecision but obviously the book i'm reading neglected to mention that.
Joseph
+8  A: 

The default precision for cout in C++ is 6 digits, and so 2001.3666 will display as 2001.37, but 201.3666 should display as 201.367.

You can increase the precision like this:

#include <iomanip>
...
cout << "you entered " << setprecision(10) << numberWithDecimalPlaces << endl;
NeilDurant
Thanks for the help, looks like setprecision rounds itself and I ended up spending a hour making code to do the rounding with math, thanks heaps for the quick replies.
Joseph