从文本框中删除数字
我在文本框“84,8441546842904”中有这个数字如何在按钮点击事件中转换为84,8或84,84?
如果你的意思是你想要解析值并将其四舍五入到一定数量的小数位:
double value = Math.Round(double.Parse(textbox.Text), 2);
将解析文本并将其四舍五入到小数点后两位。 解析时可能需要使用System.Globalization.CultureInfo对象来考虑本地区域文化的数字格式。
请参阅http://msdn.microsoft.com/en-us/library/75ks3aby.aspx
看起来你似乎试图将数字修剪为1或2精度(不是’,’在某些国家用作美国’。’?)。 如果这是您所追求的,您可以使用Double.Parse将其转换为Double,然后查看此处描述的字符串格式选项,将其格式化回文本框。
我使用这种函数来validation用户输入。
这种问题的方法也尊重用户文化数字格式!
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()); }