System.Double.Parse not accurate?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I've got a section of code in my app that keeps track of how much time an
employee has accrued, which equals out to 1.33 days of PTO per month. I'm
trying to store the time accrued so far in an XML file. I have no problems
writing to and reading from the XML file and all my values are correct. The
problem I'm having is my calculation never amounts to 1.33, it goes from
1.32999999999997
to
1.3743333333333.
on the next run.

My calculation is
int TimePerDay = 1.33 /
DateTime.DaysInMonth(DateTime.Parse(DateTime.Now.ToShortDateString()).Year,
DateTime.Parse(DateTime.Now.ToShortDateString()).Month);

I save the difference of that calculation in the XML file, and then retrieve
it again when the calculation is necessary. Here is the code:
int TimeCount =
System.Double.Parse(xmlDoc.ChildNodes.Item(1).ChildNodes.Item(1).InnerText);
//the first time I retrieve this value, it will be initially set to
0.0443333333333333
//the first time this code runs
TimeCount += 1.33 /
DateTime.DaysInMonth(DateTime.Parse(DateTime.Now.ToShortDateString()).Year,
DateTime.Parse(DateTime.Now.ToShortDateString()).Month);
xmlDoc.Save(Path);

Like I said the problem is that calculation never amounts to 1.33 - I have
ran it many times in a for loop without ever converting it to a string value.
The for loop eventually calculates to 1.33, and it stops at 1.33 and
displays that fact in a MessageBox. I think I may be having a problem with
the System.Double.Parse parser . . . anybody got any idea's? :)
 
slylos said:
I've got a section of code in my app that keeps track of how much
time an employee has accrued, which equals out to 1.33 days of PTO
per month. I'm trying to store the time accrued so far in an XML
file. I have no problems writing to and reading from the XML file
and all my values are correct. The problem I'm having is my
calculation never amounts to 1.33, it goes from
1.32999999999997
to
1.3743333333333.
on the next run.

See
http://www.yoda.arachsys.com/csharp/floatingpoint.html

for the reasons floating point calculations come out "wrong"

Hans Kesting
 
The article you provided was very useful. Thank you very much for that
information. Now let me get back to my code and see what I come up with!
 
I found that if I take the
NewTime variable, which I read the latest floating point value into from the
XML file, if I modulo it by 1.33, I eventually get 1.33 exact when NewTime
actually sums to 1.33000000000012. I can then check for the modulo value to
get the desired result. Thanks for your help all!!
 
Back
Top