.net 使用String.Format在运行时指定小数位数
我想使用String.Format指定要显示的小数位数,在运行时小数位数可能会更改 通常我会这样做:.net 使用String.Format在运行时指定小数位数,.net,vb.net,precision,numeric,string.format,.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("M
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))
但不必把绳子拧成一团。有什么方法可以做到这一点吗?不连接字符串,您可以这样做
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)))
您可以创建一个扩展名,将值格式化为具有所需位数的字符串。它隐藏了函数中实现的细节,但使其与
ToString
一样易于使用:
公共函数ToStringPlaces(值为十进制,位为整数)为字符串
'ToDo:错误检查
返回String.Format(value.ToString(“f”&places.ToString))
端函数
测试:
据我所知,没有。我能想到的最好办法是嵌套你的
string.Format
调用,这太糟糕了。我很想把格式转换成您传递的格式:string.format(“…places is{1}”,places,d.ToString(“f”+places))代码>。我知道,它们都很讨厌,但至少你要处理的是一个常量格式的字符串。
Private pi As Decimal = 22/7
'...
Label1.Text = pi.ToStringPlaces(3)
==> 3.142