[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now


Check for Integer or Decimal value

Posted on 2008-11-06
Medium Priority
Last Modified: 2012-06-27
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
Question by:Jimbo99999
  • 4
  • 3
  • 2
  • +2
LVL 25

Accepted Solution

SStory earned 1000 total points
ID: 22895041
Trapping an error is not a good way to check for an integer. This is expensive.
LVL 60

Assisted Solution

by:Kevin Cross
Kevin Cross earned 1000 total points
ID: 22895178
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

LVL 16

Expert Comment

ID: 22895291
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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.


Author Comment

ID: 22895875
mwvisa1 I am not sure I understand what you mean ---> ...to test if you have a whole number of decimal

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

thanks for your help,
LVL 25

Expert Comment

ID: 22896104
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

Author Closing Comment

ID: 31513898
Thanks for the help.
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 22896659
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

LVL 60

Expert Comment

by:Kevin Cross
ID: 22896726
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.
LVL 25

Expert Comment

ID: 22898543
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.
LVL 60

Expert Comment

by:Kevin Cross
ID: 22898643
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.
LVL 25

Expert Comment

ID: 22898859
Yes, his way does seem best.

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you're writing a .NET application to connect to an Access .mdb database and use pre-existing queries that require parameters, you've come to the right place! Let's say the pre-existing query(qryCust) in Access takes a Date as a parameter and l…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…
Suggested Courses
Course of the Month19 days, 11 hours left to enroll

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question