views:

1687

answers:

3

Is there an efficient method in VB to check if a string can be converted to a double?

I'm currently doing this by trying to convert the string to a double and then seeing if it throws an exception. But this seems to be slowing down my application.

Try
    ' if number then format it.
    current = CDbl(x)
    current = Math.Round(current, d)
    Return current
Catch ex As System.InvalidCastException
    ' item is not a number, do not format... leave as a string
    Return x
End Try
+6  A: 

Try looking at Double.TryParse() if you are using .NET 2.0/3.0/3.5

Kane
+3  A: 
Dim text As String = "123.45"
Dim value As Double
If Double.TryParse(text, value) Then
    ' text is convertible to Double, and value contains the Double value now
Else
    ' Cannot convert text to Double
End If
Patrick McDonald
A: 

VB.NET Sample Code

Dim A as String = "5.3"
Dim B as Double

B = CDbl(Val(A)) '// Val do hard work

'// Get output 
MsgBox (B) '// Output is 5,3 Without Val result is 53.0