从小数中删除尾随零的最佳方法

Best way to remove trailing zeros from a Decimal

我有一个计算,returns一个小数,最多保留两位小数。我想要实现的是不包含小数点零的结果,因此 8.00 显示为 8,8.10 显示为 8.1,8.12 显示为 8.12。

我一直在研究数学函数,但找不到任何东西来实现这一点 - 谁能给我指出正确的方向?

根据您的描述,听起来您使用的是 Fixed-point 格式,而您应该使用 Number 格式或 General 格式。

取自 MSDN 的示例代码展示了如何使用 Number 格式:

Dim dblValue As Double = -12445.6789
Console.WriteLine(dblValue.ToString("N", CultureInfo.InvariantCulture))
' Displays -12,445.68
Console.WriteLine(dblValue.ToString("N1", _
                  CultureInfo.CreateSpecificCulture("sv-SE")))
' Displays -12 445,7 

Dim intValue As Integer = 123456789
Console.WriteLine(intValue.ToString("N1", CultureInfo.InvariantCulture))
' Displays 123,456,789.0 

有关格式化程序的完整列表,请查看此 MSDN article

您是在谈论 VB 小数数据类型吗?如果是这样,请从 MSDN 文档中阅读此内容...

Trailing Zeros. Visual Basic does not store trailing zeros in a Decimal literal. 
However, a Decimal variable preserves any trailing zeros acquired computationally. 
The following example illustrates this. 

Dim d1, d2, d3, d4 As Decimal 

d1 = 2.375D
d2 = 1.625D
d3 = d1 + d2
d4 = 4.000D

MsgBox("d1 = " & CStr(d1) & ", d2 = " & CStr(d2) & 
     ", d3 = " & CStr(d3) & ", d4 = " & CStr(d4))

The output of MsgBox in the preceding example is as follows: 

    d1 = 2.375, d2 = 1.625, d3 = 4.000, d4 = 4

因此,由于 Decimal 数据类型在计算中保留有效数字,因此您可能希望将数据类型转换为 double 并使用自定义格式,如 {0:#.##} 用于显示

MSDN Decimal Data Type

正如 Benjamin Leinweber 在其中一条评论中指出的那样,这可能是它显示为字符串的产物。也就是说,您可以采用胶带方法,像这样去掉您不想要的尾随数字(谁不经常喜欢胶带):

    ' Hacky, I did this because Visual Studio removes the 0 in the editor
    Dim num As Decimal = CDec("8.10")

    ' This will now output 8.10
    Console.WriteLine(num)

    ' Put it in a string then trim off the 0's and then the decimal place if it then happens to be at the end
    Dim buf As String = num.ToString
    buf = buf.TrimEnd("0")
    buf = buf.TrimEnd(".")

    ' This will output 8.1
    Console.WriteLine(buf)

.ToString("###") 或小数点左边有多少八角鱼。

如果你想要...比如说,小数点后两位:

.ToString("###.##")

您可以使用 TrimEnd 函数来完成:

Dim number1 As Double = 8.0
Dim number2 As Double = 8.1
Dim number3 As Double = 8.12
Console.WriteLine(number1.ToString("N2").TrimEnd("0"c).TrimEnd("."c))
Console.WriteLine(number2.ToString("N2").TrimEnd("0"c).TrimEnd("."c))
Console.WriteLine(number3.ToString("N2").TrimEnd("0"c).TrimEnd("."c))

请考虑使用 "F0" 格式化也会删除 1000 个分隔符。

此解决方案适用于不同的文化并适用于以零结尾的整数

` Public 模块 DecimalExt

<Extension()>
Function ToStringWithoutZeros(ByRef value As Decimal) As String
    Dim buf As String = value.ToString("n10")
    buf = buf.TrimEnd("0").TrimEnd(",").TrimEnd(".")
    Return buf
End Function

结束模块 `