Regex real number - c#

I need real numbers in TextBox. I try my code online here
"^-{0,1}[0-9]{1,3},{0,1}[0-9]{1,2}$"
and its working perfectly, but in my project not working.
Please show me how I must do it

Would TryParse works for you? From MSDN:
Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.
And for you, it could be something like this:
private void c_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
double num;
e.Handled = double.TryParse(e.Text, out num);
// if e.Text is a number, e.Handled will be true and num = e.Text
}

Related

Calculator - thousand separator by comma in c#

private void TextBox_TextChanged(object sender, EventArgs e)
{
string value = TextBox.Text.Replace(",", "");
double dbl;
if (double.TryParse(value, out dbl))
{
TextBox.TextChanged -= TextBoxTextChanged;
TextBox.Text = string.Format("{0:#,#0}", dbl);
TextBox.SelectionStart = TextBox.Text.Length;
TextBox.TextChanged += TextBoxTextChanged;
}
}
I used above code for making Calculator. I want to get results comma with decimal value. I want to type 1,234.1234 in the
textBox, but I can not type 1,234.1234 in the Text Box. I mean comma with decimal value not getting.
Can anybody kindly please help me to solve this problem ?
You have to provide a Culture that uses . as thousands sign.
Normally you want to use the users current culture.
double.TryParse(value, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.CurrentCulture, out dbl)
Try this:
int value = 300000
String.Format("{0:#,###0}", value);
// will return 300,000
http://msdn.microsoft.com/en-us/library/system.string.format.aspx

Texbox Copies Another Textbox in C#

I'm using WinForm. I have 2 textboxes.
Goal: I want textBox1 to mirror the numbers I type in textBox2
Problem: All numbers work, except when I type in 0 in the beginning.
Test Case:
textBox1 = 1203 - correct works
textBox2 = 1203 - correct works
textBox1 = 0123 - works
textBox2 = 123 - Does not match textBox1
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
int numb1, result;
numb1 = Convert.ToInt32(textBox1.Text);
result = numb1;
textBox2.Text = result.ToString();
}
catch (Exception)
{
textBox2.Text = "";
}
}
That's expected due the conversion of your Text string to a number. A leading zero is meaningless in a number and when you convert that number back to a string there will be no leading zero. So, just copy the Text property without conversion.
However, if this code is a tentative to validate the input then use Int32.TryParse instead of Convert.ToInt32
private void textBox1_TextChanged(object sender, EventArgs e)
{
int numb1;
if(Int32.TryParse(textBox1.Text, out numb1))
textBox2.Text = textBox1.Text;
else
{
MessageBox.Show("Invalid number");
textBox2.Text = "";
}
}
Int32.TryParse remove the necessity to use a try/catch because if the conversion fails it just return false. Instead Convert.ToInt32 raises an exception. In general terms, if you have the possibility to avoid an exception, then use that possibility instead of drive your logic catching excetions
try this:
textBox1.Text = int.Parse(textBox2.Text) == 0 ? "0" : textBox2.Text;

Math.Round a label in C#

i am trying to round my output to 2 decimals in C#. My code works correctly, it writes what i want to my label, but it refuses to round it to 2 decimals. Can anyone help me with this? The commented math.round code is what I tried an got no errors with. It doesn't work for me tho.
private void button1_Click(object sender, EventArgs e)
{
try
{
double input;
double number = 0.484;
double output;
input = Convert.ToDouble(textBox1.Text);
output = Convert.ToDouble(input / number);
label1.Text = output.ToString();
//output = Math.Round(output, 2);
//Math.Round(output, 2);
}
catch
{
// Do nothing
It is too late to round the output after you have set its pre-rounding value to the label. You need to round the value first, and then set it, like this:
label1.Text = Math.Round(output, 2).ToString();
However, rounding for display purposes is not the best way of doing things: you would be better off formatting the value to two decimal places.
You should write the output formatted:
label1.Text = output.ToString("N2");
Or, if you don't want CultureInfo thousands separator:
label1.Text = output.ToString("0.00");
You can do like this to get 2 decimals
label1.Text = string.Format("{0:N2}%", output.ToString());
Try this one :
label1.Text = output.ToString("#.##");
Change this statment it will work fine.

TextBox Validation - C#

I am having quite a hard time with my C# Application's textbox validation. The thing is, the said textbox should only accept decimal values. so it means, there should be no letters or any other symbols aside from the '.' symbol. The letter filter, i can handle. However, i don't exactly know how I can manage to filter the number of '.' that the textbox should accept. If anybody has any idea how to do this, please give me an idea.
Thank you very much :)
decimal value;
bool isValid = decimal.TryParse(textBox.Text, out value);
if (!isValid)
{
throw new ArgumentException("Input must be a decimal value");
}
this should work!!!
modified for just one decimal
private void txtType_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Back || (e.KeyChar == (char)'.') && !(sender as TextBox).Text.Contains("."))
{
return;
}
decimal isNumber = 0;
e.Handled = !decimal.TryParse(e.KeyChar.ToString(), out isNumber);
}
Use regex validation:
^([0-9]*|\d*\.\d{1}?\d*)$
This site has a library of regex validation (including numeric related) that you'll find useful:
http://regexlib.com/Search.aspx?k=decimal&c=-1&m=-1&ps=20
Just a thought: if you are monitoring the decimal places, simply keep a bool flag in your control to say "I've already had a dot"; subsequent dots are invalid.
Alternatively, when checking for decimal places, you can use Contains:
if (textbox.Text.Contains("."))
Also, review this sample available on MSDN (NumericTextBox):
http://msdn.microsoft.com/en-us/library/ms229644(VS.80).aspx
Use a MaskedTextBox instead and set the mask to only accept decimals.

How do I detect a NumberDecimalSeparator in a KeyDown event (C#)

I'm trying to see if the user has pressed a decimal separator in a text box, and either allow or suppress it depending on other parameters.
The NumberdecimalSeparator returns as 46, or '.' on my US system. Many other countries use ',' as the separator. The KeyDown event sets the KeyValue to 190 when I press the period.
Do I just continue to look for commas/periods, or is there a better way?
The call
CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator
gets the decimal separator for the current user interface culture. You can use other cultures to get the separator for other languages.
EDIT
From the 166 cultures that are reported in my system (CultureInfo.GetCultures(CultureTypes.SpecificCultures).Count()), it seems that only two separators are used: period and comma. You can try this in your system:
var seps = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
.Select(ci => ci.NumberFormat.NumberDecimalSeparator)
.Distinct()
.ToList();
Assuming that this is true, this method may be helpful (note that the keyCode is OR'ed with the modifiers flag in order to eliminate invalid combinations):
private bool IsDecimalSeparator(Keys keyCode, Keys modifiers)
{
Keys fullKeyCode = keyCode | modifiers;
if (fullKeyCode.Equals(Keys.Decimal)) // value=110
return true;
string uiSep = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator;
if (uiSep.Equals("."))
return fullKeyCode.Equals(Keys.OemPeriod); // value=190
else if (uiSep.Equals(","))
return fullKeyCode.Equals(Keys.Oemcomma); // value=188
throw new ApplicationException(string.Format("Unknown separator found {0}", uiSep));
}
A last note: According to Keys enumeration, the value 46 that you mention corresponds to the DEL (Delete) key (i.e. the point when Num Lock is OFF).
The problem here is that the values in the KeyEventArgs are key codes, not characters. If you handle KeyPress instead, you will get a char in the KeyPressEventArgs which you can use for the comparison.
Note: You should really compare the NumberDecimalSeparator characters as it is a string, not a single character so you need to consider scenarios where there is more than one character in the string.
If you need know if the char pressed is decimal separator:
private void Control_KeyPress(object sender, KeyPressEventArgs e)
{
char separator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];
if (e.KeyCahr == separador)
{
// true
}
else
{
// false
}
}
But, if you need acept decimal numpad key as decimal separator of any culture:
private bool decimalSeparator = false;
private void Control_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Decimal)
decimalSeparator = true;
}
private void Control_KeyPress(object sender, KeyPressEventArgs e)
{
if (decimalSeparator)
{
e.KeyChar = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];
decimalSeparator = false;
}
}

Categories