VB - Convert long String-number to Integer - vb.net

Alright, so I'm not exactly very oriented when it comes to functions available in VB.
I have a string containing the current date and time and need to convert it to a integer so i can compare the time.
Dim my_str as String = "201308281110"
Dim my_int as Integer = Convert.ToInt32(my_str)
I cant do that with this string apparently. Because I think it is too long for the 32-bit integer. All the other convertions I have tried also fails. That including "ToInt64", "Int", "CInt"... So, any idea how to convert this longer string to an integer?

Why don't you just simply use Date? You can compare Dates with each other, so there's no need to use an integer for comparing.
Dim my_date as Date = DateTime.ParseExact(my_str, "yyyyMMddhhmm", System.Globalization.CultureInfo.InvariantCulture)

Normally I wouldn't do this. Several correct answers have already been given, but since you are still learning VB.NET, I feel like a more thorough answer would be helpful to you. So my answer will repeat some of what others have already said.
The Int64 and Decimal types are indeed big enough to to hold a number like that. I suspect that the reason why Convert.ToInt64 wasn't working for you is because you were trying to store the results in an Integer variable, like this:
Dim my_str as String = "201308281110"
Dim my_int as Integer = Convert.ToInt64(my_str) ' Throws an OverflowException
The reason that fails is not because ToInt64 doesn't work. That part of the statement is actually working fine. The part that's failing is where you are assigning the my_int variable to the value. my_int is declared as an Integer. The Integer type in VB.NET is actually just a pseudonym for Int32. In other words, it's actually the same thing as this:
Dim my_str as String = "201308281110"
Dim my_int as Int32 = Convert.ToInt64(my_str) ' Throws an OverflowException, just like the above example
To correct the problem, you need to change the type of the my_int variable to Int64 so that it will be big enough to hold the value being returned from the ToInt64 function.
Dim my_str as String = "201308281110"
Dim my_int as Int64 = Convert.ToInt64(my_str) ' Works
In VB.NET, Long is the pseudonym for Int64, so in most cases, that's what you should use. If you are going to use Long, however, using the ToInt64 method is a little ugly. It would be easier to read to just use Long on both sides of the assignment, like this:
Dim my_str as String = "201308281110"
Dim my_int as Long = Long.Parse(my_str) ' Works, just like above
That also makes the code marginally safer because it will still work even if the size of Long changes in the future (however unlikely that may be).
The Decimal type would also be large enough to hold the value, but it would be less efficient than using Long, so I wouldn't recommend it.
This begs the question, however, "Why are you doing this?" If you need to compare the value to another Long variable, it would make sense to do that, but then how did you get that other Long value? If you are converting both Long values from strings, then it doesn't make sense to do that. The string is already formatted in a way where it can be easily compared with other strings of the same format. For instance:
Dim dateTime1 As String = "201308281110"
Dim dateTime2 As String = "201308281850"
If dateTime1 > dateTime2 Then
' Doesn't get here
End If
If dateTime1 < dateTime2 Then
' Get's here
End If
If dateTime1 = dateTime2 Then
' Doesn't get here
End If
If, however, you need to parse the value to read its individual parts (e.g. date, time, year, month, hour), it makes more sense to convert the value to a DateTime value. Or, if you need to compare the string value to another value which is already stored in a DateTime variable, then, in that case, it also makes sense to convert the string to a DateTime value. In VB.NET, the pseudonym for DateTime is simply Date, so in most cases, you should just use that, like this:
Dim my_str as String = "201308281110"
Dim my_date as Date = Date.ParseExact(my_str, "yyyyMMddHHmm", System.Globalization.CultureInfo.InvariantCulture)
If my_date > Date.Now Then
' Do stuff
End If

But Long.Parse works as well as Convert.ToInt64 since it doesn't overflow(Int32.MaxValue is 2147483647):
Dim myLong1 = Long.Parse("201308281110")
Dim myLong2 = System.Convert.ToInt64("201308281110")
Demo
Note that Long is the same as Int64.

Related

Negative result in HEX to DEC vb.net

Need help in converting hex to dec in VB.NET
I use the code below in smaller number which returns the expected result.
leftPaddingHex = Val("&H" & "99000533")
but when using 99000533 it return negative result -1728051917. I am expecting to get 2566915379. I am using to get the correct result in ms sql. using the code below.
CONVERT(BIGINT,CONVERT(varbinary(4),(SELECT master.dbo.fn_cdc_hexstrtobin(#leftPadding))))
Need help on this. Thanks in advance.
Thank you.
Aze
I just thought that I'd post this alternate method.
The various integer type's Parse and TryParse methods allow you to specify a System.Globalization.NumberStyles parameter. You can specify the System.Globalization.NumberStyles.AllowHexSpecifier to parse a hexadecimal string. The only restriction is that the string can not be prefixed with "0x" or "&h".
Dim unsigned32 As UInt32
Dim itParsed As Boolean = UInt32.TryParse("99000533", System.Globalization.NumberStyles.AllowHexSpecifier, Nothing, unsigned32)
The Val method returns Double. This cannot be changed
One workaround would be to use Long data type in the final result (that is, your leftPaddingHex) and to check if the result in the intermediate stage is negative, we add it with UInt.MaxValue + 1 to correct it:
Dim leftPaddingHex As Long = Val("&H" & "99000533")
If leftPaddingHex < 0 Then
leftPaddingHex = leftPaddingHex + UInt32.MaxValue + 1
End If
For hexadecimal with even larger number, I suggest you to take a look on this

What is used for holding String values in vb.net

hi I would just like to ask
if Val(Textbox1.Text) is for holding values of integers.
what should I put when holding values for String??
Textbox1.Text is a string, so a simple string variable will work:
Dim s As String = Textbox1.Text
But, note that Val doesnt "hold" a value but is a function to convert a string to a value. And it always returns a Double, not Integer.
To convert a string to Integer use Convert.ToInt32 or CInt. When working with TextBoxes though where the user may enter illegal data such as "123foo45", you should test the contents to avoid an error:
Dim n As Integer
If Integer.TryParse(TextBox1.Text, n) Then
' text can parse, n holds the value
Else
' tell the user they entered bad info
End If

Difference between CType(str,DateTime) and DateTime.Parse(str)

I want to convert str into DateTime.
For that which option should I used in VB.NET? And Why?
I tend to do it like this:
Dates "disguised" as Object
If I know the object is a datetime I use CType:
Dim table As New DataTable("Table")
table.Columns.Add("DATETIME_COLUMN", GetType(DateTime))
table.Rows.Add(Date.Now)
table.AcceptChanges()
Dim d As DateTime = CType(table.Rows(0).Item("DATETIME_COLUMN"), DateTime)
Strings
When dealing with strings I use DateTime.Parse. Notice that you can pass a cultureinfo.
Dim d As DateTime = DateTime.Parse("10.02.2014", New System.Globalization.CultureInfo("nb-NO"))
Unknown/mixed types
Finally, if I cannot be sure of the datatype, I use Convert.ToDateTime:
Dim d As DateTime = Convert.ToDateTime(obj, New System.Globalization.CultureInfo("nb-NO"))
CType & CDate are VB.NET functions that have defined functionality.
Ctype('01/01/2014',DateTime)
DateTime.Parse is a BCL (Base class library) method that has defined
functionality.
Dim value As String = "2000-02-02"
Dim dt As DateTime = DateTime.Parse(value)
As long as your string is in the right date format, you can just use CDate() function. This is the fastest and easiest way since you only have to type 7 characters excluding the string to be converted :) In terms of efficiency and speed, doesn't really make a difference.

Assigning nothing to double from reader with no data [duplicate]

This question already has answers here:
Preserving NULL values in a Double Variable
(3 answers)
Closed 8 years ago.
NOTE: This issue does not pertain exclusively to Null values, it relates more specifically to non double values and handling them through the reader convert assignment.
Looking for a way to check for blanks or non double values in this reader value before the reader throws an error on the Convert....
Dim Load_Pc As Double = Convert.ToDouble(reader("Load_Pc"))
Is there some way to assign nothing to Load_Pc if the reader is blank or not able to handle the value?
Since you say "blanks", i assume that the actual type of the column is string.
Then you could either use Double.TryParse or check if it's null or empty
Dim ordinalIndex = reader.GetOrdinal("Load_Pc")
Dim Load_Pc As Double = Double.MinValue
If Not reader.IsDbNull(ordinalIndex) Then
Dim loadPC As String = reader.GetString(ordinalIndex)
If Not String.IsNullOrWhiteSpace(loadPC) Then
Load_Pc = Double.Parse(loadPC)
End If
End If
Here the TryParse approach:
Double.TryParse(reader.GetString(ordinalIndex), Load_Pc)
However, if possible you should always store the correct type, never string/varchar for a numeric value or DateTime. Then it would be more efficient and less error-prone:
Dim Load_Pc As Double = reader.GetDouble(ordinalIndex)
If you want to use a Nullable(Of Double) instead:
Dim Load_Pc As Double? = Nothing
Dim dLoad_Pc As Double
If Double.TryParse(reader.GetString(ordinalIndex), dLoad_Pc) Then
Load_Pc = dLoad_Pc
End If
With a Double, the answer is no.
With a Double?, however, the answer would be yes. For more info check nullable types.

String.ToCharArray() stored in StringCollection conversion to numbers and back in VB.net

I have a string which was converted to a char array and stored in a stringcollection, how do I return the numerical value for the character in each string? How can I reverse this process, getting the character from the numerical value?
I know I could code a Select Case statement, but that would take a very long time as I need to cover every character a person could want to conceivably use in the English language, including punctuation.
Is there already a method built into vb.net for doing this?
Thanks for the help!
The Convert class has methods that can convert between characters and integers:
Dim c As Char = "A"C
Dim i As Integer = Convert.ToInt32(c)
Dim c2 As Char = Convert.ToChar(i)
To loop the values converted from the characters in a string into an array of integers:
Dim codes(theString.Length - 1) As Integer
For i As Integer = 0 to theString.Length - 1
codes(i) = Convert.ToInt32(theString.Chars(i))
Next
Try something like this:
For Each c As Char In yourString
Dim i As Int32 = DirectCast(c, Int32)
Next
Remeber that System.String implements IEnumerable<Char> so it is legal to For Each over it. And converting between a character and a number is as simple as casting between System.Char and System.Int32 (here I have shown how to get the numeric value for each character in the string).