验证TextBox控件中输入是否是两位小数,不是则自动更正

/// <summary>
        /// 当焦点离开时,验证是否保留了两位小数,如不是自动更正
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtUnitPrice_Leave(object sender, EventArgs e)
        {
            string content = txtUnitPrice.Text;
            string[] str = content.Split('.');
            if (str[0] == string.Empty)
            {
                str[0] = "0";
            }
            if (str.Length > 2)
            {
                MessageBox.Show("您输入的数字不正确!"); return;
            }
            if(str.Length==2)
            {
                if (str[1].Length > 2)
                {
                    str[1].Remove(2);
                }
                else if(str[1].Length==2)
                {

                }
                else if (str[1].Length == 1)
                {
                    str[1] += "0";
                }
                else if (str[1].Length == 0)
                {
                    str[1] += "00";
                }
            }
            else
            {
                txtUnitPrice.Text = str[0] + ".00"; return;
            }
            txtUnitPrice.Text = str[0] + "." + str[1];
        }

 

posted @ 2012-05-09 00:12  易水寒2012  阅读(278)  评论(0编辑  收藏  举报