【问题标题】:Using String.Format to specify the decimal places at runtime在运行时使用 String.Format 指定小数位
【发布时间】:2014-10-01 04:30:46
【问题描述】:

我想使用 String.Format 指定小数位数以显示小数位数在运行时可能发生变化的位置。

通常我会这样做:

Dim d As Decimal = 1.23456D
Debug.WriteLine(String.Format("My number to 2 decimal places is {0:f2}", d))

我想做的是这样的:

Dim d As Decimal = 1.23456D
Dim places as integer = 2
Debug.WriteLine(String.Format("My number to {0} decimal places is {1:f" + places.ToString + "}", places, d))

但不必连接字符串。有没有办法做到这一点?

【问题讨论】:

  • 据我所知,没有。我能想到的最好的办法是嵌套你的string.Format 调用,这会很糟糕。不过,我很想将格式提取到您传递的格式中:string.Format("...places is {1}", places, d.ToString("f" + places));。我知道,它们每一种都很恶心,但至少你正在处理一个常量格式字符串。

标签: .net vb.net precision numeric string.format


【解决方案1】:

不用连接字符串,你可以这样做

 Dim d As Decimal = 1.23456D
 Dim places As Integer = 2
 Debug.WriteLine(String.Format("My number to {0} decimal places is {1}", places, Decimal.Round(d, places)))

【讨论】:

    【解决方案2】:

    您可以创建一个扩展来将值格式化为具有所需位置数的字符串。它将实现的细节隐藏在一个函数中,但使它像ToString一样易于使用:

    <Extension()>
    Public Function ToStringPlaces(value As Decimal, places As Integer) As String
        ' ToDo: error checking
        Return String.Format(value.ToString("f" & places.ToString))
    End Function
    

    测试:

    Private pi As Decimal = 22/7
    '...
    Label1.Text = pi.ToStringPlaces(3)
    
    ==> 3.142
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-23
      • 1970-01-01
      • 2018-12-22
      相关资源
      最近更新 更多