我希望我的程序输入一个十进制小数,通过不舍入输入的数字输出4位小数
输入:0.6363636364
输出:0.6363
答案 0 :(得分:0)
为了完整性,由于OP请求VB解决方案,这里是基于Tim Lloyd对Truncate Two decimal places without rounding的回答的Decimal扩展:
Module MyExtensions
<System.Runtime.CompilerServices.Extension>
Public Function TruncateDecimal(d As Decimal, decimals As Integer) As Decimal
Select Case True
Case decimals < 0
Throw New ArgumentOutOfRangeException("decimals", "Value must be in range 0-28.")
Case decimals > 28
Throw New ArgumentOutOfRangeException("decimals", "Value must be in range 0-28.")
Case decimals = 0
Return Math.Truncate(d)
Case Else
Dim IntegerPart As Decimal = Math.Truncate(d)
Dim ScalingFactor As Decimal = d - IntegerPart
Dim Multiplier As Decimal = Math.Pow(10, decimals)
ScalingFactor = Math.Truncate(ScalingFactor * Multiplier) / Multiplier
Return IntegerPart + ScalingFactor
End Select
End Function
End Module
用法:
Dim Value As Decimal = 0.6363636364
Value = Value.TruncateDecimal(4)