Click here to Skip to main content
15,888,273 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,


According to msdn defenition for rounding methods :

-----------------------------------------------------------------------------------------------
ToEven - When a number is halfway between two others, it is rounded toward the nearest even number.
AwayFromZero - When a number is halfway between two others, it is rounded toward the nearest number that is away from zero.
-----------------------------------------------------------------------------------------------

however when trying to use Math.Round i get these results :

double x1 = Math.Round(2.1125, 3, MidpointRounding.ToEven); // Result 2.112
double x2 = Math.Round(2.1125, 3, MidpointRounding.AwayFromZero); // Result 2.113
double x3 = Math.Round(2.1135, 3, MidpointRounding.ToEven); // Result 2.114
double x4 = Math.Round(2.1135, 3, MidpointRounding.AwayFromZero); // Result 2.114

double y1 = Math.Round(2.125, 2, MidpointRounding.ToEven); // Result 2.12
double y2 = Math.Round(2.125, 2, MidpointRounding.AwayFromZero); // Result 2.13
double y3 = Math.Round(2.135, 2, MidpointRounding.ToEven); // Result 2.13
double y4 = Math.Round(2.135, 2, MidpointRounding.AwayFromZero); // Result 2.13

when rounding 3 decimals the result is expected.
but when rounding 2 decimals I get a wrong result.

y3 should return 2.14 because we are rounding to EVEN numbers.
y4 should return 2.14 becuase we are rounding away from zero.

I dont understand the results. Can anyone please explain them to me ?



Eldad.
Posted
Comments
Richard MacCutchan 5-May-13 3:18am    
Floating point numbers always produce strange results because of the way they are represented in computers; they are approximations of real numbers.

1 solution

See the "Notes to Callers" on MSDN's page about this method: Math.Round(Double, Int32, MidpointRounding)[^]: "Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, Int32, MidpointRounding) method may not appear to round midpoint values as specified by the mode parameter. ..."
Regards,
Ian.
 
Share this answer
 
Comments
nguyenvansutt 23-Jul-14 1:21am    
So how I can round 2.135 -- >2.14 ?
thanks
Ian A Davidson 23-Jul-14 2:31am    
Do you mean, how can you overcome the rounding problem?
I expect people have written numerous articles on it, because it is a problem all computers have in one form or another due to the way floating point numbers work.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900