문자열을 이중 -VB로 변환합니다
문제
문자열을 더블로 변환 할 수 있는지 확인하는 VB에 효율적인 방법이 있습니까?
나는 현재 문자열을 더블로 변환하려고 시도한 다음 예외가 발생하는지 확인 함으로써이 작업을 수행하고 있습니다. 그러나 이것은 내 응용 프로그램을 늦추고있는 것 같습니다.
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
해결책
.NET 1.1/2.0/3.0/3.5/4.0/4.5를 사용하는 경우 double.tryparse ()를보십시오.
다른 팁
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
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
국제 버전 :
Public Shared Function GetDouble(ByVal doublestring As String) As Double
Dim retval As Double
Dim sep As String = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
Double.TryParse(Replace(Replace(doublestring, ".", sep), ",", sep), retval)
Return retval
End Function
' NULLABLE VERSION:
Public Shared Function GetDoubleNullable(ByVal doublestring As String) As Double?
Dim retval As Double
Dim sep As String = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
If Double.TryParse(Replace(Replace(doublestring, ".", sep), ",", sep), retval) Then
Return retval
Else
Return Nothing
End If
End Function
결과:
' HUNGARIAN REGIONAL SETTINGS (NumberDecimalSeparator: ,)
' Clean Double.TryParse
' -------------------------------------------------
Double.TryParse("1.12", d1) ' Type: DOUBLE Value: d1 = 0.0
Double.TryParse("1,12", d2) ' Type: DOUBLE Value: d2 = 1.12
Double.TryParse("abcd", d3) ' Type: DOUBLE Value: d3 = 0.0
' GetDouble() method
' -------------------------------------------------
d1 = GetDouble("1.12") ' Type: DOUBLE Value: d1 = 1.12
d2 = GetDouble("1,12") ' Type: DOUBLE Value: d2 = 1.12
d3 = GetDouble("abcd") ' Type: DOUBLE Value: d3 = 0.0
' Nullable version - GetDoubleNullable() method
' -------------------------------------------------
d1n = GetDoubleNullable("1.12") ' Type: DOUBLE? Value: d1n = 1.12
d2n = GetDoubleNullable("1,12") ' Type: DOUBLE? Value: d2n = 1.12
d3n = GetDoubleNullable("abcd") ' Type: DOUBLE? Value: d3n = Nothing
나는 간단하게 사용했다 Eval(string)
그리고 그것은 이중으로 평가되었습니다.
제휴하지 않습니다 StackOverflow