Search code examples
c#roundingmath.round

how to do to get accurate result of rounding value


Math.Round() not working properly

Round(17.675, 2) is getting 17.68

Round(6.675, 2) also getting 6.68

But Round(36.675, 2) is getting 36.67

same like Round(38.675, 2) is getting 38.67enter image description here

but when I Round(28.675, 2) is getting 28.68

I used all optional parameters, then also getting same result

How to resolve this ? pls help me


Solution

  • You can use the Round(Double, Int32, MidpointRounding) overload and specify the MidpointRounding parameter to get the desired rounding strategy.

    MidpointRounding is an enum with these values (from the original documentation):

    AwayFromZero 1 The strategy of rounding to the nearest number, and when a number is halfway between two others, it's rounded toward the nearest number that's away from zero.
    ToEven 0 The strategy of rounding to the nearest number, and when a number is halfway between two others, it's rounded toward the nearest even number.
    ToNegativeInfinity 3 The strategy of downwards-directed rounding, with the result closest to and no greater than the infinitely precise result.
    ToPositiveInfinity 4 The strategy of upwards-directed rounding, with the result closest to and no less than the infinitely precise result.
    ToZero 2 The strategy of directed rounding toward zero, with the result closest to and no greater in magnitude than the infinitely precise result.

    The default is MidpointRounding.ToEven. This is why it rounds sometimes up and sometime down. I.e., it round the midpoint values to the nearest even whole number.

    Also note that double values might not be what they appear to be. E.g. 36.675 could be stored as 36.67499999999999. If you need a more reliable rounding, e.g. for money calculations, use decimal instead. The documentation for the System.Decimal struct says:

    The Decimal value type is appropriate for financial calculations that require large numbers of significant integral and fractional digits and no round-off errors.