Why is it that when I do the following...
Math.Round(0.75, 1, MidpointRounding.AwayFromZero)
I get 0.8
but when I do the following...
Math.Round(0.575, 2, MidpointRounding.AwayFromZero)
I don't get 0.58. Instead I get 0.57. I want anything that is 5 and up rounding up, so 0.575 should be 0.58.
This question is related to
.net
vb.net
math-functions
It is caused by a lack of precision with doubles / decimals (i.e. - the function will not always give the result you expect).
See the following link: MSDN on Math.Round
Here is the relevant quote:
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.This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14.This occurs because internally the method multiplies value by 10digits, and the multiplication operation in this case suffers from a loss of precision.
The System.Math.Round
method uses the Double
structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round
method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:
Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)
Result: 0.58
Source: Stackoverflow.com