将文本框限制为小数点后 1 位。Winform C#

use*_*356 0 c# winforms

我正在使用 c# 开发一个 winform 应用程序,我已经成功实现了一种将文本框限制为小数点后两位的方法。我怎样才能做到精确到小数点后一位。?

我的代码保留两位小数。\

private void txtHraRep_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsNumber(e.KeyChar) || e.KeyChar == '.')
            {
                if (Regex.IsMatch(
                 txtHraRep.Text,
                 "^\\d*\\.\\d{2}$")) e.Handled = true;
            }
            else e.Handled = e.KeyChar != (char)Keys.Back;
        }
Run Code Online (Sandbox Code Playgroud)

更改 为 "^\d*\.\d{1}$")) e.Handled = true;

输出

这是输出

Say*_*yse 5

您可以在不使用正则表达式的情况下执行此操作,只需检查文本中小数点分隔符的位置,然后确保它比字符串的长度小 2 位(小数点后 1 位,数组长度少 1 位)

var decSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
var idx = txtBasic.Text.IndexOf(decSeparator);
if(idx + 2 >= txtBasic.Text.Length)
    ...
Run Code Online (Sandbox Code Playgroud)