从文本框中删除数字

本文关键字:删除 数字 文本 | 更新日期: 2023-09-27 18:17:43

我有这个数字在文本框"84,8441546842904"如何转换在84,8或84,84上按钮点击事件?

从文本框中删除数字

如果您的意思是要解析该值并将其四舍五入到小数位数:

double value = Math.Round(double.Parse(textbox.Text), 2);

将解析文本并将其舍入到小数点后2位。在解析时,您可能需要使用System.Globalization.CultureInfo对象来解释本地区域性的数字格式。

见http://msdn.microsoft.com/en-us/library/75ks3aby.aspx

看起来就像你试图将数字修剪为1或2的精度(','在某些国家不是像美国的'.'一样使用吗?)如果这是你想要的,你可以用Double。解析将其转换为Double类型,然后查看这里描述的字符串格式选项,将其格式化回文本框。

我使用这种函数来验证用户输入。

这种解决问题的方法也尊重用户文化号码格式!

namespace Your_App_Namespace
{
public static class Globals
{
    public static double safeval = 0; // variable to save former value!
    public static bool isPositiveNumeric(string strval, System.Globalization.NumberStyles NumberStyle)
    // checking if string strval contains positive number in USER CULTURE NUMBER FORMAT!
    {
        double result;
        boolean test;
        if (strval.Contains("-")) test = false;
        else test = Double.TryParse(strval, NumberStyle, System.Globalization.CultureInfo.CurrentCulture, out result);
               // if (test == false) MessageBox.Show("Not positive number!");
        return test;
    }
    public static string numstr2string(string strval, string nofdec)
    // conversion from numeric string into string in USER CULTURE NUMBER FORMAT!
    // call example numstr2string("12.3456", "0.00") returns "12.34"
    {
        string retstr = 0.ToString(nofdec);
        if (Globals.isPositiveNumeric(strval, System.Globalization.NumberStyles.Number)) retstr = double.Parse(strval).ToString(nofdec);
        else retstr = Globals.safeval.ToString(nofdec);
        return retstr;
    }
    public static string number2string(double numval, string nofdec)
    // conversion from numeric value into string in USER CULTURE NUMBER FORMAT!
    // call example number2string(12.3456, "0.00") returns "12.34"
    {
        string retstr = 0.ToString(nofdec);
        if (Globals.isPositiveNumeric(numval.ToString(), System.Globalization.NumberStyles.Number)) retstr = numval.ToString(nofdec);
        else retstr = Globals.safeval.ToString(nofdec);
        return retstr;
    }
}
// Other Your_App_Namespace content
}
    // This is the way how to use those functions
    // function to call when TextBox GotFocus
    private void textbox_clear(object sender, System.Windows.RoutedEventArgs e)
    {
        TextBox txtbox = e.OriginalSource as TextBox;
        // save original value
        Globals.safeval = double.Parse(txtbox.Text);
        txtbox.Text = "";
    }
    // function to call when TextBox LostFocus
    private void textbox_change(object sender, System.Windows.RoutedEventArgs e)
    {
        TextBox txtbox = e.OriginalSource as TextBox;
        // text from textbox into sting with checking and string format
        txtbox.Text = Globals.numstr2string(txtbox.Text, "0.00");
    }
double i = 0;
if (double.TryParse(tbxNumber.Text,out i)) {
    MessageBox.Show("number is " + i.ToString());
}