Pete's Windows, Office, VB & SQL Blog

Problems I have solved (or not) and good ideas I've found

Archive for September 2009

Function optional variable as integer = nothing defaults to zero

leave a comment »

The following code does not work because the value of ‘places’ is zero not nothing
Sub Main()
Dim a As Double = 1.034567
Dim b As Double = 1.434588
If DeciUnEq(a, b) Then
Console.WriteLine(“a:” & a.ToString & ” NOT EQUALS b:” & b.ToString & ” to five decimal places”)
Else
Console.WriteLine(“a:” & a.ToString & ” IS EQUAL b:” & b.ToString & ” to five decimal places”)
End If
a = b
Console.WriteLine(“Complete, press return to exit”)
Console.ReadLine()
End Sub

Public Function DeciUnEq(ByVal Vala As Double, ByVal Valb As Double, Optional ByVal places As Integer = Nothing) As Boolean
‘ Check numbers for inEquality at the specified precision level
‘ This is either passed to the routine or taken from a public variable Precision, or defaulted to 5.
If IsNothing(places) Then
places = 5
End If
If Math.Round(Vala, places) Math.Round(Valb, places) Then Return True
Return False ‘ They are equal!
End Function

Written by fisherpeter

2009 September 3 at 13:03