CodeItBetter Programming Another VB Programming Blog

How to check whether given string is numeric or not without using IsNumeric function.

Posted on January 4, 2009
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
'Controls - How to check whether given string is numeric or not without using IsNumeric function.
123,,,123
345-
0 ' What if it isn't a currency field?
' What if I don't want to support scientific notation?

'To cope with this issue, I have prepared an alternative function, which you can
'modify for your particular purposes. (For instance, you can add support for a
'currency symbol or the comma as the decimal separator.) Note that this function
'always returns True when it's passed a null string, so you might need to
'perform additional tests if the user isn't allowed to leave the field blank:

Function CheckNumeric(Text As String, DecValue As Boolean) As Boolean
    Dim I As Integer
    For I = 1 To Len(Text)
        Select Case Mid$(Text, I, 1)
        Case "0" To "9"
        Case "-", "+"
            ' Minus/plus signs are only allowed as leading chars.
            If I > 1 Then Exit Function
        Case "."
            ' Exit if decimal values not allowed.
            If Not DecValue Then Exit Function
            ' Only one decimal separator is allowed.
            If InStr(Text, ".") < I Then Exit Function
        Case Else
            ' Reject all other characters.
            Exit Function
        End Select
    Next
    CheckNumeric = True
End Function
Filed under: Controls Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


 

No trackbacks yet.