转换十进制是删除我的零

时间:2016-01-12 00:57:59

标签: vb.net

我怎样才能确保结果不会删除最后的0,例如,这会产生" 1.454"而不是" 1.4540"

    Dim test1 As Decimal = 14540
    Debug.Print(TransformDecimal(test1, 1))

Private Shared Function TransformDecimal(value As Decimal, numberOfPlaces As Integer) As Decimal
    Dim min = CDec(Math.Pow(10, numberOfPlaces - 1))
    Dim max = CDec(Math.Pow(10, numberOfPlaces))

    If (value >= max) Then
        While value >= max
            value /= 10
        End While
    ElseIf (value < min) Then
        While value < min
            value *= 10
        End While
    End If

    Return value
End Function

1 个答案:

答案 0 :(得分:2)

你真的必须Option Explicit On

如果您没有,并且您拥有此代码Dim x As Decimal = 1.0,则表示您正在创建Double,然后将其转换为Decimal。使用Option Strict On,此代码将无法编译。

当您编写此代码Dim x As Decimal = 1.0d时,您会立即创建Decimal - 并保留小数位。

所以,如果你现在写这样的方法:

Private Shared Function TransformDecimal(value As Decimal, numberOfPlaces As Integer) As Decimal
    Dim min = CDec(Math.Pow(10, numberOfPlaces - 1))
    Dim max = CDec(Math.Pow(10, numberOfPlaces))

    If (value >= max) Then
        While value >= max
            Dim bits = Decimal.GetBits(value)
            bits(3) = ((bits(3) \ 65536) + 1) * 65536
            value = New Decimal(bits)
        End While
    ElseIf (value < min) Then
        While value < min
            Dim bits = Decimal.GetBits(value)
            bits(3) = ((bits(3) \ 65536) - 1) * 65536
            value = New Decimal(bits)
        End While
    End If

    Return value
End Function

并称之为:

Dim test1 As Decimal = 14540d
Debug.Print(TransformDecimal(test1, 1).ToString())

你会发现你得到了你想要的结果:

1.4540

此代码的关键是行bits(3) = ((bits(3) \ 65536) + 1) * 65536&amp; bits(3) = ((bits(3) \ 65536) - 1) * 65536移动指数以十进制的倍数更改小数。