3
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.

4

4 回答 4

7

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))
于 2012-08-30T19:50:25.597 回答
4

You can use:

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

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

于 2012-08-30T19:49:05.607 回答
1

Use

Math.Round(value, 2, System.MidpointRounding.AwayFromZero)
于 2012-08-30T19:50:07.307 回答
1

Check out the MidpointRounding parameter:

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

Should give you 43.57

于 2012-08-30T19:51:14.237 回答