4
Module Module1
Public Sub Main()
    Dim values() As Double = {43.523, 12.65, 43.565}
    For Each value As Double In values
        Console.WriteLine("{0} --> {1}", value, Math.Round(value, 2))
    Next
    Console.ReadLine()
End Sub
End Module

The above code results as

  • 43.523 --> 43.52

  • 12.65 --> 12.65

  • 43.565 --> 43.56

I need 43.565 --> 43.57 and not 43.565 --> 43.56. But i still need the other 43.523 --> 43.52 and 12.65 --> 12.65 rounded as is.

Marcer
  • 839
  • 1
  • 12
  • 25
  • But note that "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." For `Round(43.565,2,mode)`, it does, since although the `Double` closest to 43.565 is smaller than that, multiplying by 100 yields exactly 4356.5, so the value rounded to an integer _is_ a midpoint. But for 2.135, you get 2.13, since the rounded value isn't a midpoint. – Daniel Fischer Aug 30 '12 at 21:54

4 Answers4

8

Firstly, if exact decimal values are of concern to you, you should consider using Decimal instead of Double. In particular, 43.565 isn't exactly representable as a Double to start with.

However, if you want to specify the behaviour for "midpoints" (i.e. where it could reasonably round up or down), use the overload with a MidpointRounding parameter:

Console.WriteLine("{0} --> {1}", value, _
                  Math.Round(value, 2, MidpointRounding.AwayFromZero))
Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

You can use:

Math.Round(value, 2, MidpointRounding.AwayFromZero)

For details, see the overload of Math.Round which accepts a MidpointRounding.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
1

Use

Math.Round(value, 2, System.MidpointRounding.AwayFromZero)
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
1

Check out the MidpointRounding parameter:

Math.Round(43.565, 2, MidpointRounding.AwayFromZero)

Should give you 43.57

Mike Christensen
  • 88,082
  • 50
  • 208
  • 326