

Title  Round numbers to a given number of digits without using banker's rounding in Visual Basic 2005 
Description  This example shows how to round numbers to a given number of digits without using banker's rounding in Visual Basic 2005. 
Keywords  round, banker's rounding, digits, VB 2005 
Categories  Miscellany, Tips and Tricks 


Normally Visual Basic uses "banker's rounding." In banker's rounding, numbers with final digit 5 are rounded to the nearest even number, not to the next larger number. The idea is that statistically half of a sample of numbers are rounded up and half are rounded down.
The following code rounds numbers to a certain number of digits and rounds up if a number's final digit is 5.


Private Function NonBankersRound(ByVal num As Double, ByVal _
digits As Integer) As Double
Dim factor As Double = 10 ^ digits
num = Int(num * factor + 0.5) / factor
Return num
End Function


When you change the number in the program's TextBox, the code displays the number rounded to 1, 2, 3, and 4 digits past the decimal point using banker's rounding and nonbanker's rounding so you can see the difference.





