23

文字列を double に変換できるかどうかを確認する VB の効率的な方法はありますか?

現在、文字列を 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
4

5 に答える 5

26

.NET 1.1 / 2.0 / 3.0 / 3.5 / 4.0 / 4.5を使用している場合は、Double.TryParse()を確認してください。

于 2009-07-23T14:53:21.997 に答える
24

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
于 2009-08-26T18:46:04.573 に答える
12
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
于 2009-07-23T15:10:12.063 に答える