Check for Integer or Decimal value

Good Day


Currently I have the following code for checking if a value is an Integer in one of my programs.  This works great.  However, I need to integrate the ability to validate for a decimal value as well.  If decimal
then it should be valid as well.  How can I adjust this code to check for both?


Dim chkForInt As Integer
     chkForInt = Integer.Parse(Matrix.Columns.Item("NumEntry").Cells.Item(i).Specific.Value())
      g_B1Connection.Application.MessageBox("Value entered is not an Integer: " & (Matrix.Columns.Item("NumEntry").Cells.Item(i).Specific.Value()), 1, "OK")
      ErrFlag = "1"
      Exit Sub
End Try
Who is Participating?
SStoryConnect With a Mentor Commented:
Trapping an error is not a good way to check for an integer. This is expensive.
Kevin CrossConnect With a Mentor Chief Technology OfficerCommented:
SStory showed how to check if IsNumeric, so once you are in that block of code where you know the value is numeric then you can use this to test if you have a whole number of decimal.

Something like this may work:
If Math.Round(Double.Parse("2.5"), 0) <> Double.Parse("2.5") Then
        End If

Open in new window

IMHO, it is poor programming practice to use exceptions to accomplish a task.  In other words, exceptions are just that, exceptions.  They shouldn't ever be the expected execution path.

So I personally would have written a subroutine that either utilizes some of the various 'Is' functions (IsDate, IsNumeric, etc) or converted the value to a string and simply iterate through the string looking for non-numeric characters (for integers) or non-numeric characters save a single decimal point.

While I don't have anything handy to check for decimal v. non-decimal, I'll provide the following subroutine I've used in VB6 to take a string and strip out everything that didn't belong in a floating point number.  Obviously not what you were looking for, but if you do want to write your own routine, you could utilize some of these concepts
'Given a String, remove everything from the string that could not be interpreted as a floating point number
' 12.3ABC45.6 => 12.3456
Public Function StripToFloat$(Data As String)
Dim Ch As String * 1
Dim DecimalPoint As Boolean   'Has a Decimal Point Been Found
Dim NegativeSign As Boolean   'Has a Negative Sign Been Found
Dim I As Integer
'Allow a Leading or Trailing '-' to indicate a negative Number
'but only if the sign abuts the first or last number in the string...
' '-10' or '10-' would be negative
' neither '- 10' nor '10 -' would be negative
' neither '10-10' nor '10 - 10' nor '10- 10' nor '10 -10' would be negative
'Save the FIRST Period found in the string as a Decimal Point
    DecimalPoint = False
    NegativeSign = False
    For I = 1 To Len(Data)
        Ch = Mid$(Data, I, 1)
        If "0" <= Ch And Ch <= "9" Then
            StripToFloat$ = StripToFloat$ & Ch
        ElseIf Ch = "." Then
            If Not DecimalPoint Then
                StripToFloat$ = StripToFloat$ & Ch
            End If
        'NOTE: Any Logic Change to interpretation of Negative Sign should also be done in StripToInt
        ElseIf Ch = "-" Then        '07/09/97 Addition of Negative Signs
            If Not NegativeSign Then    'Can only Find one negative sign
                If Len(StripToFloat$) = 0 Then     'If NO numerics have been found AND...
                    Ch = Mid$(Data, I + 1, 1)       'If next char is a numeric then
                    If "0" <= Ch And Ch <= "9" Then '   this is a negative sign
                        NegativeSign = True
                    End If
                Else    'Length is > 0
                    If Len(StripToFloat$(Mid$(Data, I + 1))) = 0 Then 'If no additional numerics to the right AND...
                        Ch = Mid$(Data, I - 1, 1)                       'If previous char is a numeric then
                        If "0" <= Ch And Ch <= "9" Then                 '   this is a negative sign
                            NegativeSign = True
                        End If
                    End If
                End If
            End If
        End If
    Next I
    If NegativeSign Then
        StripToFloat$ = "-" & StripToFloat$
    End If
End Function

Open in new window

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Jimbo99999Author Commented:
mwvisa1 I am not sure I understand what you mean ---> test if you have a whole number of decimal

what is the Double.Parse("2.5") code doing ?

thanks for your help,
I agree that it is a poor practice to use exceptions to handle things...unless there is no other way.

In Dotnet to see if it is a decimal or not  you could do

if IsNumeric(myvar) then
    if myvar.tostring.indexof(".")=-1 then
        'it is an integer--no "." was found
        'it has a decimal place
    end if
   'not a number
end if
Jimbo99999Author Commented:
Thanks for the help.
Mike TomlinsonMiddle School Assistant TeacherCommented:
Hi Jimbo99999,

I believe you are using VB.Net 2005 right?

Use the Integer.TryParse() and Decimal.TryParse() methods:

An example:

        Dim value As String = Matrix.Columns.Item("NumEntry").Cells.Item(i).Specific.Value()
        Dim intValue As Integer
        Dim decValue As Decimal

        If Integer.TryParse(value, intValue) OrElse Decimal.TryParse(value, decValue) Then
            ' ...It was a VALID Integer or Decimal...
            g_B1Connection.Application.MessageBox("Value entered is not an Integer or Decimal: " & value, 1, "OK")
            ErrFlag = "1"
        End If

Kevin CrossChief Technology OfficerCommented:
If you test for index of ".", IMHO, is not appropriately telling you if you have a decimal value or an Integer as you can end up with 25.0 which is an Integer value from my interpretation and 25.1 is a decimal.  

If you are looking for whether the value is written with decimal points I would agree.

Therefore, to answer your question Jimbo99999, I was doing this:

+"2.5" represents your variable coming in as string with a value that has numeric value
+I would usually recommend Double.TryParse here, but since SStory's suggestion already go you in a true portion of an IF statement that validated IsNumeric then Double.Parse was used to convert the string to actual number value, specifically a Double which allows decimals.  This could have been Decimal.Parse.

Math.Round(Double.Parse("2.5"), 0)
+Following same logic as above, the inner portion of code gets you numeric value of your variable.
+Rounding to zero decimal places gets you whole number (Integer).  Another method would be say Math.Floor.

Then by comparing the two you will know if you have a decimal versus an Integer written with a .0 after it.


25 = 25.0
25 <> 25.4
26 <> 25.8

Hope that makes sense.
mwvisa1, It is true that 25.0 would fail.  In the previous VB rounding never seemed to work like I would think.  I was concerned about rounding errors.  I guess if the new Round works better then it might be OK.
Kevin CrossChief Technology OfficerCommented:
I didn't see Idle_Mind's post until after I posted -- that is what I use more than trusting round, but it does work better in .NET.
Yes, his way does seem best.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.