.net - 使用 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("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)))

关于.net - 使用 String.Format 在运行时指定小数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26117202/

相关文章:

.net - ADO.NET Entity Framework 和 Linq to Entities

.net - ASP.NET 从 NTLM 身份验证表单获取用户名和密码

c# - ADO.NET DataTable 约束如何影响性能?

vb.net - 字节转换回图像

c# - 使用 Math.Round 的舍入问题

c# - "not this string"的 .NET 正则表达式

c# - 使用 linq 获取一组元素

hibernate - JPA 注释不保留 BigDecimal 精度

python - 如何在 float32 而不是 float64 上强制执行 python float 操作?

scala - 输出 Scala Double 以创建与 Python 兼容的字符串