954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Decimals lost when converting

I think I have a convertingproblem when using stringstream.
I multiply 0.995 * 19.99 wich is: 19.89005

The first messageBox do show because 19.89 < 19.89005.

Then I convert Total to string and back to double again and do
the same check if: 19.89 < NewNumber
But here the MessageBox doesn´t show so I beleive there is something
that happens with the decimals when converting like I do. (Red Area)
Is it possible to not lose decimals when doing a conversion to string and back to
double like I do ?
Wonder if this is the problem that I think.

double Total = 0.995 * 19.99;  //Gives 19.89005
std::string Replacing;

if( 19.89 < Total )
{
      MessageBox::Show("Before");
}	
/*................................................*/

stringstream c1;
c1 << Total; 
Replacing = c1.str();

double NewNumber = 0;
stringstream v1(Replacing);
v1 >> NewNumber ;
if( 19.89 < NewNumber )
{
     MessageBox::Show("After");
}
Jennifer84
Posting Pro
564 posts since Feb 2008
Reputation Points: 10
Solved Threads: 1
 

change the precision of the stringstream

stringstream c1;
   c1.precision(100);
   c1 << Total; 
   Replacing = c1.str();
dougy83
Posting Whiz in Training
275 posts since Jun 2007
Reputation Points: 85
Solved Threads: 45
 

Change c1 << Total; to: c1 << std::setprecision(10) << Total;

And don't forget to #include <iomanip> for this.

[edit]Darn, too slow

Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 

The trick is to use fixed
c1 << fixed << setw(6) << Total;

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

That did solve the problem. setw(6) should then meen to put 6 characters as I red in MSDN.
Thank you...

The trick is to use fixed c1 << fixed << setw(6) << Total;
Jennifer84
Posting Pro
564 posts since Feb 2008
Reputation Points: 10
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You