代码之家  ›  专栏  ›  技术社区  ›  awi2b

VB.Net将格式化字符串转换为双精度字符串

  •  0
  • awi2b  · 技术社区  · 2 年前

    我通过格式化一个双值得到了一个字符串,比如

    Dim strFormat = "#,##0.00 weeks"
    Dim strDisplayText As String = dblIn.ToString(strFormat) ' dblIn is type Double
    

    然后strDisplayText显示在(wpf.datagrid的)文本框中,用户可以对其进行编辑。然后,文本应该转换回双精度文本。

    Dim dblOut = ???(strDisplayText, strFormat)
     ' dblOut should be the same as dblIn, if strDisplayText wasnt changed.
    if dblOut.ToString(strFormat) <> strDisplayText Then
        print("failed conversion.")
    end if
    

    双重的由于末尾的“周”,Parse(和TryParse)失败,Val无法将“,”作为组分隔符进行处理。

    strFormat是从文件中读取的,因此它可能是任何有效的自定义或标准数字格式( https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings 或 https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings )

    1 回复  |  直到 2 年前
        1
  •  1
  •   Tim Schmelter    2 年前

    可以使用简单的字符串方法删除 " weeks" 最后:

    Dim dblValue = strDisplayText.Remove(strDisplayText.Length - " weeks".Length)
    Dim dbl As Double = double.Parse(dblValue)
    

    strFormat是从文件中读取的,因此它可能是任何有效的自定义或 标准数字格式

    不能将使用任意格式字符串格式化的文本恢复为双值。没有 Double.TryParseExact (喜欢 Date ). 尤其是如果您有不同的十进制或组分隔符。

    我会让用户编辑双值,而不是格式化的文本。