Reputation: 2042
I am trying to cast a string into an int and for some reason the following seems to work.
Dim theInt As Int32 = CInt("55e5")
Console.WriteLine("String to Int32: " & theInt)
I am having trouble understanding why it converts correctly and outputs 5500000
Upvotes: 0
Views: 76
Reputation: 2297
Where you expecting 55 as the answer? The old VB VAL() would return that.
I played with a custom .Net Val() for our code. In mostly deals with dollar signs, commas, (), but could be extended:
Public Function ValTest(ByVal value As String) As Double
If String.IsNullOrEmpty(value) Then Return 0
If IsNumeric(value) Then Return CDbl(value.Trim) ' IsNumeric and CDbl strip currency $ and comma, and support accounting negation e.g. ($23.23) = -23.23
' deal with case where leading/trailing non-numerics are present/expected
Dim result As String = String.Empty
Dim s As String = value.Trim
If s.StartsWith("(") Then s.Replace("(", "-") ' leading ( = negative number from accounting - not supported by VB.Val()
For Each c As Char In s
If Char.IsNumber(c) OrElse "-.".Contains(c) Then
result = (result + c)
End If
Next c
If String.IsNullOrEmpty(result) Then
Return 0
Else
Return CDbl(result)
End If
End Function
Upvotes: 0
Reputation: 104785
Its converting that e5
to scientific notation (think that's the proper term?), so its pushing the decimal place 5 times over, hence 5500000
(5 extra 0's)
Upvotes: 1