0

In following code if I encounter some incorrect result while I applied following input to the code.

Code is as follow.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    MsgBox(TextBox1.Text & " = Val(" & Val(TextBox1.Text) & ") = Math.Round(" & Math.Round(Val(TextBox1.Text)) & ")")
End Sub

Input applied => Output Received

3.5 => 4

5.5 => 6

4.5 => 4

Math.Round function returns correct result in first two inputs, but third result is incorrect.

Please help me to sort it out.

2 Answers2

0

The documentation says:

If the fractional component of d is halfway between two integers, one of which is even and the other odd, the even number is returned.

You can try to use:

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

You can check MidpointRounding Enumeration

enter image description here

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • What should be the code if expected result of code should as follow. if x.5 then result would be x+1? –  May 18 '16 at 05:24
0
Math.Round(4.5, 0, MidpointRounding.AwayFromZero)