【问题标题】:NumericUpDown.Value not rounded to DecimalPlacesNumericUpDown.Value 未四舍五入到 DecimalPlaces
【发布时间】:2014-02-16 12:46:53
【问题描述】:

假设我有一个 DecimalPlaces = 2 的 NumericUpDown。

用户键入“1.233”(他们不知道,不小心按了两次“3”键),然后离开控件。此输入现在在控件中显示为“1.23”。但是, Value 属性现在是 1.233 。 因此,在用户看来他们正在使用值 1.23,而实际上他们正在使用值 1.233。 有什么方法可以让 NumericUpDown 返回“正确”的值:1.23?

我了解 DecimalPlaces 属性“...设置要显示的小数位数”,但用户无法通过简单地阅读屏幕来确定将使用什么值。

一种方法是始终忽略所有 NumericUpDowns 的 Value 属性,而只使用 Text 属性(从 IntelliSense 中隐藏)并对该属性执行 decimal.Parse() - 但这看起来很尴尬。另一点是,如果用户键入“1.233”然后离开控件,那么当 ValueChanged 事件发生时,Text 属性仍然是“1.233”。

【问题讨论】:

  • 这有点丑,但你可以绑定到ValueChanged 事件,并在其中有这样的东西numericUpDown1.Value = Math.Truncate(100 * numericUpDown1.Value) / 100
  • 它确实应该在文档中 NumericUpDowns 不四舍五入的地方;也许更好的问题是,为什么他们圆?这种行为有什么好处吗?

标签: c# numericupdown


【解决方案1】:

是的。 Validating 事件对于调整数据输入总是有用的。像这样:

    private void numericUpDown1_Validating(object sender, CancelEventArgs e) {
        numericUpDown1.Value = Math.Round(numericUpDown1.Value, 
            numericUpDown1.DecimalPlaces, MidpointRounding.AwayFromZero);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-12
    • 2012-08-04
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    相关资源
    最近更新 更多