Question

I have written a rather primitive shared function to evaluate a numerical value entered into a textbox. A user can enter a decimal or an integer and the range I am evaluating against is 5.0 to 14.0. The first two parts of the if statement return true, but the last part returns false for the number of decimals when an integer is input and the absence of a decimal point. How can I modify this function to return true on all paths please?

Public Shared Function CheckDecimalValue(ByVal txtbox As TextBox) As Boolean
    Dim returnValue As Boolean = True
    Dim txtAsDecimal As Decimal = CType(txtbox.Text, Decimal)
    Dim decimalAsString As String = CType(txtAsDecimal, String)
    Dim indexOfDecimalPoint As Integer = decimalAsString.IndexOf(".")
    Dim numberOfDecimals As Integer = decimalAsString.Substring(indexOfDecimalPoint + 1).Length

    If txtAsDecimal < 5 Then
        returnValue = False
    ElseIf txtAsDecimal > 14 Then
        returnValue = False
    ElseIf numberOfDecimals > 1 Then
        returnValue = False
    End If

    Return returnValue
End Function
Était-ce utile?

La solution

Really, just use Decimal.TryParse.

If the user uses a different culture where . is not the decimal seperator, your code breaks anyway.

Example:

Public Shared Function CheckDecimalValue(txtbox As TextBox) As Boolean
    Dim tmp As Decimal
    Return Decimal.TryParse(txtbox.Text, tmp) AndAlso tmp >= 5 AndAlso tmp <= 14
End Function

Autres conseils

Would strongly suggest using Decimal.TryParse instead:

eg:

Public Shared Function CheckDecimalValue(ByVal txtbox As TextBox) As Boolean

    Dim val as Decimal

    If Not Decimal.TryParse(txtbox.Text,val) Then Return False

    If val < 5 Or val > 14 Then Return False

    'Space for other checks

    Return True

End Function
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top