Skip to content

Instantly share code, notes, and snippets.

@vbjay
Created February 23, 2019 13:28
Show Gist options
  • Save vbjay/95accc155ae194f7392472cd32aead6f to your computer and use it in GitHub Desktop.
Save vbjay/95accc155ae194f7392472cd32aead6f to your computer and use it in GitHub Desktop.
Shows Number handling in vb
Sub Main
Dim input = {"12", "-643", "12.58", "12.5485758797457348957437", "$34,566,776", "C345a55t", "Cat"}
Dim results = input.Select(Function(i) New With {
.Input = i,
.Integer = GetInteger(i),
.Long = getlong(i),
.Single = GetSingle(i),
.Double = GetDouble(i),
.Decimal = GetDecimal(i),
.Val = GetVal(i)
})
Dim valid = results.Select(Function(r) New With {
.Input = r.Input,
.Integer = r.Integer.HasValue,
.Long = r.Long.HasValue,
.Single = r.Single.HasValue,
.Double = r.Double.HasValue,
.Decimal = r.Decimal.HasValue,
.Val = r.Val.HasValue,
.ResultValue = r
})
Dim ifs = results.Select(Function(r) New With {
.Input = r.Input,
.Integer = If(r.Integer, 99),
.Long = If(r.Long, 99L),
.Single = If(r.Single, 99!),
.Double = If(r.Double, 99#),
.Decimal = If(r.Decimal, 99D),
.Val = If(r.Val, 99D),
.ResultValue = r
})
Dim defaults = results.Select(Function(r) New With {
.Input = r.Input,
.Integer = r.Integer.GetValueOrDefault(99),
.Long = r.long.GetValueOrDefault(99L),
.Single = r.Single.GetValueOrDefault(99!),
.Double = r.Double.GetValueOrDefault(99#),
.Decimal = r.Decimal.GetValueOrDefault(99D),
.Val = r.Val.GetValueOrDefault(99D),
.ResultValue = r
})
results.Dump("Number values")
valid.dump("Numbers are valid numbers")
ifs.Dump("Use if to get defaults if null")
defaults.Dump("Use GetDefaultValue to get defaults if null")
End Sub
' Define other methods and classes here
Function GetInteger(input As String) As Integer?
Dim num As Integer
If Integer.TryParse(input, num) Then Return num
Return Nothing
End Function
Function GetLong(input As String) As Long?
Dim num As Long
If Long.TryParse(input, num) Then Return num
Return Nothing
End Function
Function GetSingle(input As String) As Single?
Dim num As Single
If Single.TryParse(input, num) Then Return num
Return Nothing
End Function
Function GetDouble(input As String) As Double?
Dim num As Double
If Double.TryParse(input, num) Then Return num
Return Nothing
End Function
Function GetDecimal(input As String) As Decimal?
Dim num As Decimal
If Decimal.TryParse(input, num) Then Return num
Return Nothing
End Function
Function GetVal(i As String) As Double?
Try
Return Val(i)
Catch ex As Exception
Return Nothing
End Try
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment