.NET NumericUpDown with Decimals = AsNeeded

时间:2016-03-28 10:05:42

标签: c# .net vb.net

我需要进行循环计算,其中3个NumericUpDown控件中的任何一个都会更改其值。所有这些控件都将属性'DecimalPlaces'设置为2.但是如果我想在循环计算中获得正确的结果,我需要更多的小数。

所以现在我需要一个NumericUpDown控件(不太重要)让可更改的小数位表示'AsNeeded'。

例如,如果数字是1.2345,则控制应该设置4位小数,如果是0.10,它们应该有1位小数来显示数字。
当然我希望这个属性自动更改需要显示的数字。

有任何建议让NumericUpDown控件以这种方式工作吗?

1 个答案:

答案 0 :(得分:2)

只需根据需要设置NumericUpDown控件显示的小数位数:

Private Sub NumericUpDown1_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown1.ValueChanged
    Dim ud = DirectCast(sender, NumericUpDown)
    Dim val = Math.Abs(ud.Value)
    Dim frac = (val - Math.Truncate(val)).ToString().TrimEnd({"0"c})
    ud.DecimalPlaces = Math.Max(frac.Length - If(val < 0, 3, 2), 0)
End Sub

我们只对数字的小数部分感兴趣。我们不希望任何尾随零。

当转换为字符串时,分数将有两个前导字符(零和小数分隔符),除非它是负数,在这种情况下有三个前导字符(减号,零和小数分隔符)。

如果您对通过字符串获取小数位数感到不满意,那么您可以这样做:

Private Function Frac(d As Decimal) As Decimal
    d = Math.Abs(d)
    Return d - Math.Truncate(d)
End Function

Private Function NumberOfDecimals(x As Decimal) As Integer
    x = Math.Abs(x)
    Dim nPlaces = 0

    While Frac(x) > 0
        x = x * 10D
        nPlaces += 1
    End While

    Return nPlaces

End Function

Private Sub NumericUpDown1_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown1.ValueChanged
    Dim ud = DirectCast(sender, NumericUpDown)
    ud.DecimalPlaces = NumberOfDecimals(ud.Value)
End Sub

应该适用于您想要使用NumericUpDown控件的值范围。我不想将该方法与Double或Single一起使用,因为很多小数都没有用浮点格式表示。

请注意,技术上0.1与0.10不同 - 前者可以表示[0.05,0.15]范围内的数字,后者[0.95,1.05]。