我的计算返回一个小数,最多有两位小数。我想要实现的是不包含十进制零的结果,因此8.00显示为8,8.10显示为8.1,8.12显示为8.12。
我已经完成了数学功能,无法找到任何实现这一目标 - 有人能指出我正确的方向吗?
答案 0 :(得分:3)
正如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(New String({"0", "."})) ' trim off the 0's and then the decimal place if it then happens to be at the end at the end
' This will output 8.1
Console.WriteLine(buf)
答案 1 :(得分:2)
您是在谈论VB Decimal数据类型吗?如果是,那么请从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:#.##}
进行显示)
答案 2 :(得分:1)
.ToString("###")
或者在小数点左边有多少octothorpes。
如果你想...说,2位小数:
.ToString("###.##")
答案 3 :(得分:1)
您可以使用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个分隔符。
答案 4 :(得分:0)
根据您的描述,当您使用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。
答案 5 :(得分:0)
此解决方案适用于不同的文化,适用于以零结尾的整数
` 公共模块 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
结束模块 `