使用String.Format在运行时指定小数位

时间:2014-09-30 09:23:35

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

我想使用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))

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

2 个答案:

答案 0 :(得分:3)

如果没有连接字符串,你可以这样做

 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)))

答案 1 :(得分:1)

您可以创建一个扩展名,将值格式化为字符串,并显示所需的位置数。它隐藏了函数中实现的细节,但使其与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