Public Function Round(Number As Decimal, places As Integer) As Decimal 'Convert number to string Dim NumberString As String = Number.ToString 'Check if the number contains a decimal, if not return the number If NumberString.IndexOf("."c) = -1 Then Return Number 'Get the whole number part of the string Dim IntegerPart As String = NumberString.Split("."c)(0) 'Get the Decimal part of the string Dim DecimalPart As String = NumberString.Split("."c)(1) 'If the number is already rounded to n decimal places, then return the number If DecimalPart.Length = places Then Return Number 'Get whichever decimals are being rounded to Dim ToPlacePart As String = DecimalPart.Substring(0, places) 'get the other part that will be compared Dim ComparePart As String = DecimalPart.Substring(places) 'Create a midpoint to compare the compare part to Dim ControlMidPoint As Decimal = Decimal.Parse("1" & Replace(Space(ComparePart.Length), Space(1), "0")) / 2 'Create the base result(Add the integer part to the decimal part that will stay) Dim Result As Decimal = Decimal.Parse(IntegerPart & "." & ToPlacePart) 'Create an increment to add if the comparepart is greater than the mid point(ex 0.001, 0.01, 0.0000001) Dim AddNum As Decimal = Decimal.Parse("0." & Replace(Space(ToPlacePart.Count - 1), Space(1), "0") & "1") 'If the comparepart was equal to or greater than the midpoint, then add the addpart to the base result and return it If Decimal.Parse(ComparePart) >= ControlMidPoint Then Return Result + AddNum 'Just return the base result, because the compare part was smaller than the midpoint Return Result End Function
source share