-1

How can I left only one "0" before "."? I'm making TextBox which accepts only digits and you can write only one "0" before ".", but you can write any numbers like 900 or 5000.

Here is the pseudocode I use:

if (0 > 1 before "." && 0 is first digit) 
{
    Remove all zeros before "." and left one; 
}

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Ovidzikas
  • 113
  • 11

5 Answers5

0

use it like this

for (int i=0;i<textbox.Text.Length;i++)
{
    textbox.Text=textbox.Text.Replace("00.","0.")
}
rashfmnb
  • 9,959
  • 4
  • 33
  • 44
0

Simplest way is probably to remove ALL of the 0 at the start;

textbox.Text = textbox.Text.TrimStart('0');

And then if it starts with '.' add a '0' back on the beginning again.

if (textbox.Text.StartsWith('.'))
    textbox.Text = '0' + textbox.Text;

This will also remove any 0 at the beginning of, for example, "00500", changing it to "500", which is probably a good thing.

Stuart Whitehouse
  • 1,421
  • 18
  • 30
0

Relaying on TextChanged event have some drawbacks. For example user may want to enter zeroes and then precede them by digit (.) symbol. Your code would delete all leading zeroes before digit is entered. It is better to use other event like Validating or LostFocus. Code would be quite simple:

textbox.Text = textbox.Text.TrimStart('0');

You may use NumericUpDown control for numeric-only input. It will validate whether text is a number and format it according to settings like DecimalPlaces.

0

Maybe this one can help:

public string ZeroPoint(string a)
{
  int pos = a.IndexOf(".");
  if (pos > -1 && a.Substring(0, pos) == new string('0', pos))
  {
    a = "0" + a.Substring(pos, a.Length - pos);
  }
  return a;
}
jackomelly
  • 523
  • 1
  • 8
  • 15
0

You need to use the KeyPress event and add the below logic to determine what is being pressed and where the entered value is going to be placed.

When you set the e.Handled value to true then you are telling the system to ignore the users input.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    // Only allow digits, decimal points and control characters (Backspace, delete, etc)
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
        (e.KeyChar != '.'))
    {
        e.Handled = true;
    }

    int PointIndex = (sender as TextBox).Text.IndexOf('.');

    // only allow one decimal point and one digit before decimal point
    if (((e.KeyChar == '.') && PointIndex > -1) || 
        (e.KeyChar == '.' && textBox1.SelectionStart > 1) ||
        (PointIndex == 1 && textBox1.SelectionStart <= PointIndex))
    {
        e.Handled = true;
    }
}

This code validates the users input as they are typing.

EDIT:

Also since this code only validates the input as the user is typing you will also want to prevent them pasting in invalid values. You can do this by setting the ShortcutsEnabled property of the textbox to false.

CathalMF
  • 9,705
  • 6
  • 70
  • 106