문제

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
도움이 되었습니까?

해결책

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top