将字符串转换为Double - VB

msc*_*ccc 21 vb.net string double try-catch

在VB中是否有一种有效的方法来检查字符串是否可以转换为double?

我目前正在尝试将字符串转换为double,然后查看是否抛出异常.但这似乎减慢了我的申请速度.

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
Run Code Online (Sandbox Code Playgroud)

Kan*_*ane 23

如果您使用的是.NET 1.1/2.0/3.0/3.5/4.0/4.5,请尝试查看Double.TryParse()


小智 21

VB.NET示例代码

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
Run Code Online (Sandbox Code Playgroud)


Pat*_*ald 11

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
Run Code Online (Sandbox Code Playgroud)