Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Convert string to double problem 2

Status
Not open for further replies.

tcstom

Programmer
Aug 22, 2003
235
GB
Hi,

I have 12 textboxes which a user must use to input monthly budget amounts. I then have a button which adds up these amounts, and if they total a pre-set annual budget amount then a save occurs. Most of the time this works fine, but I'm now finding that when the annual budget is £250 and the 12 monthly values are 6 x £35.71, 1 x £35.74 and 5 x £0.00 I get an odd result.

Basically, the following code loops through the 12 textboxes converting the value to a double and adding it to a cumulative total. On the 6th loop (when i = 5 below) it suddenly converts the text "35.71" to the double 35.71000000000002 ? ? ? That's even after converting the same text string in other textboxes correctly. Does anyone have any idea why this is happening? The loop code is very simple and I reproduce it here.

Code:
for (int i = 0; i < arrMonthBoxes.Length; i++)
{
  // if no value has been entered set it to zero
  if (arrMonthBoxes[i].Text.Length == 0)
  {
    arrMonthBoxes[i].Text = "0";
  }
  // add up all user entered values
  userDefinedTotal += Convert.ToDouble(arrMonthBoxes[i].Text);
}

Tom
emo_big_smile.gif
 
Tom,

I think you are encountering an interesting phenomena related to how computers store fractional numbers. To you an me, 35.71 seems like an easy number - 35 units plus 71 hundreths. For a computer, it has to convert that to binary. The 35 part is easy, 100011, but it's hard to make .71 out of binary fractions (eg. 1/2, 1/4, 1/8), so the computer somes as close as it can. Sometimes it's over by a little bit and sometimes it's under. If it's over repeatedly, the error can accumulate, eventually ending up in a significant digit.

Go here ( for more info.

To avoid this problem, try the following:
1) double.Parse(arrMonthBoxes.Text) instead of convert
or if that doesn't work
2) force your results to only display two decimal places

Andrew
 
That was an excellent explanation, Andrew. A star for you.

----------------------------------------

TWljcm8kb2Z0J3MgIzEgRmFuIQ==
 
Unless I'm mistaken, the Decimal type was created for currency specifically because of this problem. It would seem to be a better choice of data type.


Jeff
[purple]It's never too early to begin preparing for [/purple]International Talk Like a Pirate Day

"The software I buy sucks, The software I write sucks. It's time to give up and have a beer..." - Me
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top