I have a value in variable, say it is dim a as integer = 145.98
I tried to take the Left(a,2)
but it returned an error instead of returning 14
I also t开发者_JAVA技巧ried left(a.Tostring,2)
but error is the same.
Please help me solve it.
Thanks Furqan
First off, you say that you’re using an integer but the number is actually a floating-point number, not an integer.
Secondly, the action “take the left of a number” isn’t a meaningful operation. Left
is a substring operation, it’s only defined on strings.
You can turn the number into a string and then extract a substring of the decimal representation. This should work. What’s the error?
Finally, some general advice:
Put Option Strict On
at the very top of ever vb file, or better yet, make this option the default in your settings. Otherwise, you’ve got a veritable hullaballoo waiting to happen because VB is very … “lenient” when it comes to questionable or downright incorrect code. This option fixes this and will flag a lot more errors. For example, the compiler would (rightfully) have complained about your assignment,
Dim a As Integer = 145.98
because as I said, you’re trying to assign a floating-point number to an integer.
First of all, 145.98 is not an integer. 145 is an integer. You might want to try Double. Second, you can only take the left
of a string. You were on the right track when you added ToString, but you forgot the ()s at the end.
Dim a as Integer = 145
Dim b as Double = 145.98
Then you can do this:
Left(a.ToString(), 2)
Left(b.ToString(), 2)
Try Left(a.ToString(), 2)
instead.
If your "integer" is a string, try this:
Dim a As String = "145.98"
Dim b As Int32 = 0
Int32.TryParse(a.Substring(0, 2), b)
As Konrad has said with option strict this would not compile. If you don't have it on it will perform a conversion and store only the integer part. At this point you can call tostring
and then performe any operation on it as a string you would like.
With option strict
Option Strict On
Module Module1
Sub Main()
Dim I As Integer = CType(142.3, Integer)
Dim s As String = I.ToString
Console.WriteLine(Left(s, 2))
End Sub
End Module
With out optiion strict
Module Module1
Sub Main()
Dim I As Integer = 142.3
Dim s As String = I
Console.WriteLine(Left(s, 2))
End Sub
End Module
As you can see from the two example option strict will attempt to perform many conversions for you but does so at the risk of unexpected results.
精彩评论