我使用以下代码只取得用户的数字和只有一个小数点,这对我来说在KeyPress事件上运行正常:
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
现在我想限制小数点后面的数字/数字,即35.25468,表示点/小数后只需要6个数字/位数。
更新我!
答案 0 :(得分:4)
private void price_tb_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (!char.IsControl(e.KeyChar))
{
TextBox textBox = (TextBox)sender;
if (textBox.Text.IndexOf('.') > -1 &&
textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >= 3)
{
e.Handled = true;
}
}
}
此代码可以帮助您。它只需要一个小数位和一位小数后的两位数,你可以相应地改变它。
答案 1 :(得分:0)
在按键事件和/或验证事件上,计算小数点后的字符数。按键,按下它。在验证时,删除额外的小数位。确保你从NumberFormatInfo获得小数点字符,并非所有文化都使用'。',即。在法国,他们的小数点实际上是一个逗号
答案 2 :(得分:0)
你可以像这样添加一个额外的支票
TextBox textBox = (TextBox) sender;
if (textBox.Text.IndexOf('.') > -1 &&
textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >=3)
{
e.Handled = true;
}
注意,Substring将包含'。'因此支票是>=3
。
答案 3 :(得分:0)
在按键上,格式化字符串并将textBox.Text
设置为格式化字符串。
TextBox.Text = String.Format("{0:N3"}", textBox.Text)
此特定格式会截断小数点后三位的数字。
答案 4 :(得分:0)
我有textBox.SelectionLength == 0
允许修改所选文字:
private void price_tb_KeyPress(object sender, KeyPressEventArgs e) {
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') {
e.Handled = true;
}
TextBox textBox = (TextBox)sender;
// only allow one decimal point
if (e.KeyChar == '.' && textBox.Text.IndexOf('.') > -1) {
e.Handled = true;
}
if (!char.IsControl(e.KeyChar) && textBox.SelectionLength == 0) {
if (textBox.Text.IndexOf('.') > -1 && textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >= 3) {
e.Handled = true;
}
}
}
答案 5 :(得分:0)
我对Both FM的回答都有一个问题,就是输入小数点后两位和小数点后不能编辑文本。
此代码也要减去一个数字。
private void TextBoxAmount_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar))
{
// OK, but not more than 2 after the [.]
if (((TextBox)sender).Text.Contains('.'))
{
if (((TextBox)sender).Text.IndexOf('.') + 2 < ((TextBox)sender).Text.Length)
{
if (((TextBox)sender).SelectionStart > ((TextBox)sender).Text.IndexOf('.'))
{
e.Handled = true;
}
}
}
}
else if (char.IsControl(e.KeyChar))
{
// Always OK
}
else if (e.KeyChar == '.' && !((TextBox)sender).Text.Contains('.'))
{
// First [.] == OK
}
else if (e.KeyChar == '-' && !((TextBox)sender).Text.Contains('-'))
{
// First [-] == OK
}
else
{
e.Handled = true;
}
}
private void TextBoxAmount_KeyUp(object sender, KeyEventArgs e)
{
if (((TextBox)sender).Text.Contains('-'))
{
((TextBox)sender).Text = $"-{((TextBox)sender).Text.Replace("-", string.empty)}";
}
}