首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将字符串转换为Double - VB

将字符串转换为Double - VB
EN

Stack Overflow用户
提问于 2009-07-23 14:49:21
回答 4查看 185K关注 0票数 23

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

我目前正在尝试将字符串转换为双精度值,然后查看它是否会抛出异常。但这似乎减慢了我的应用程序。

代码语言:javascript
复制
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
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2009-07-23 14:53:22

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

票数 26
EN

Stack Overflow用户

发布于 2009-07-23 15:10:12

代码语言:javascript
复制
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
票数 12
EN

Stack Overflow用户

发布于 2015-01-13 22:59:57

国际版本:

代码语言:javascript
复制
    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

结果:

代码语言:javascript
复制
        ' 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
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1172306

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档