在做项目的时候,需要提供给用户只能输入2为小数的功能。只允许用户输入数字的情况,自然用控件NumericUpDown,同时,该控件有个属性NumericUpDown.DecimalPlaces,该属性为:默认值为 0。单独靠这个属性,显示输入2为小数,可以。但是Value还是输入的数字。嗯,用Decimal.Round();Decimal.Floor(),再或者是截取字符串,觉得都不合适。我是这么做的:

 1  private void numericUpDown1_KeyPress(object sender, KeyPressEventArgs e)
 2         {
 3             if (((NumericUpDown)sender).Text.Trim().IndexOf('.'> -1)
 4             {
 5                 if (((NumericUpDown)sender).Text.Trim().Substring(((NumericUpDown)sender).Text.Trim().IndexOf('.'+ 1).Length >= 2)//定义小数位
 6                 {
 7                     if (!char.IsDigit(e.KeyChar) )
 8                     {
 9                         e.Handled = false;
10                     }
11                     else
12                     {
13                         e.Handled = true;
14                     }
15                 }
16             }
17         }

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-16
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-09
  • 2022-12-23
  • 2017-11-25
相关资源
相似解决方案