Me.bCancel = New Button()
Me.bCancel.Parent = Me
Me.bCancel.Bounds = New Rectangle(10, 50, 150, 30)
Me.bCancel.Text = "Cancel"
AddHandler Me.bCancel.Click, AddressOf Me._Click
End Sub 'New
Private Sub _Click(o As Object, e As EventArgs)
Me.Hide()
Me.myParent.DialogResultCallback(IIf(o Is Me.bOK, DialogResult.OK, DialogResult.Cancel))
End Sub '_Click
Protected Overrides Sub OnClosing(e As CancelEventArgs)
e.Cancel = True
Me.Hide()
Me.myParent.DialogResultCallback(DialogResult.Cancel)
End Sub 'OnClosing
End Class 'ModelessDialog
7.40. How do I round floating point numbers efficiently?
There are two primary methods for rounding numbers:
Convert.ToInt32
Cast or Fix (C# or VB) Convert.ToInt32 automatically handles rounding, where remainders of .5 and greater cause the number to be rounded up. Casting or using Fix requires adding .5 to the number to ensure that it will round properly, as these methods simply remove the remainder.
Profiling on the emulator and a Compaq iPAQ H3600 series device yielded the following results for 1 million operations of each method, where num is a float set to 3.6F:
Emulator
iPAQ
Operation
Debug (ms)
Release (ms)
Debug (ms)
Release (ms)
C#: Convert.ToInt32(num)
1321
1109
6264
6283
C#: (int)(num + .5F)
170
49
1479
59
VB: Convert.ToInt32(num)
1218
1232
6531
6517
VB: Fix(num + .5F)
3873
3677
18144
17955
Thus, by examining the release build results for the device, it can be concluded that on the current generation of devices it is most efficient to use casting in C# and Convert.ToInt32 in VB. In C#, casting proved to be over 106 times faster, whereas in VB, Convert.ToInt32 was nearly 3 times faster. //C#
float temp = 3.6f;
int rounded1 = (int)(temp + .5f);
int rounded2 = Convert.ToInt32(temp);