vb.net - WRONG SUM OF DOUBLES IN VB .NET -
this question has answer here:
hello i´m using microsoft vb 2012 , have problem sum of doubles.
this simple code reproduces it:
dim result double = 0 dim amount1 double = 81.83 dim amount2 double = 50.0 result += amount1 result += amount2
result equal 131.82999999998 instead of 131.83
in fact:
dim test1 double = 81.83 + 50.0 '(= 131.82999999998 wrong) dim test2 double = 81.83 + 50 '(= 131.82999999998 wrong) dim test3 double = 81.83 + 10 '(= 91.83 ok) dim test4 double = 81.82 + 50.0 '(= 131.82 ok)
can explain it?
best regards david
a double value can represent numbers exactly. values can approximated. see wikipedia more detailed explanation. have fixed number of decimal digits, depending on size of floating point number (compare single , double) , exponent represents number. due simple calculations may produce rounding errors.
to avoid can use datatype decimal
represented , used financial calculation example avoid these errors.
Comments
Post a Comment