Returning Integer from String

D

DaveS

Hi All!

Hopefully this is an easy question...

I am trying to convert input which is read in from a text file. All
data is read in as String. What I'm trying to do is safely convert
string data to integer data, if possible, or else return nothing. For
instance,

intDatum = ConvertToInt(strDatum)

where

Function ConvertToInt (ByVal strDatum as String) As Integer
Try
Return CInt(strDatum)
Catch
Return DBNull.Value
End Try
End Function


If strDatum = "3", then intDatum = 3
If strDatum = "?", then intDatum = Nothing (DBNull.Value, whatever
works...)


TIA,

DaveS
 
H

Herfried K. Wagner [MVP]

* DaveS said:
I am trying to convert input which is read in from a text file. All
data is read in as String. What I'm trying to do is safely convert
string data to integer data, if possible, or else return nothing. For
instance,

intDatum = ConvertToInt(strDatum)

where

Function ConvertToInt (ByVal strDatum as String) As Integer
Try
Return CInt(strDatum)
Catch
Return DBNull.Value
End Try
End Function


If strDatum = "3", then intDatum = 3
If strDatum = "?", then intDatum = Nothing (DBNull.Value, whatever
works...)

Return 0, for example. Assigning 'DBNull.Value' doesn't make sense hier
since an 'Integer' cannot store this value.
 
C

Cor

Hi Dave,

Maybe your language is Dutch,
intDatum = ConvertToInt(strDatum)
And than Datum is the English Date

When that is so, than probably it is better to first convert it to the date
the date format .
(Because with the date format you can do so much more than direct to an
integer and even convert it than in a more secure way to an integer).

Did you look already at the Cdate commands to convert?

Cor
 
D

DaveS

Cor,

American English is my native language.

Datum = one piece of data.

I am simply trying to find an elegant way to convert a string number
(such as "123" to and integer 123) or return nothing at all.

I know how to accomplish the above using If..Then..End If construct.

TIA,

DaveS
 
D

DaveS

Thanks Herfried!

The function I currently use returns -1 for non-integer input. I am
looking for a way to simplify the following code:

If ValidInt (strDatum) Then
intDatum = Int32.Parse(strDatum)
End If

where

Function ValidInt (ByVal strDatum as String) As Boolean
' Returns TRUE if strDatum is an can be represented
' as an integer; otherwise FALSE
'
Dim intDatum As Integer

Try
intDatum = Int32.Parse(strDatum)
Return True
Catch
Return False
End Try
End Function

This way, if strDatum is non-integer, intDatum doesn't get assigned
anything.

TIA,

DaveS
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top