-2

I googled the web for hours but couldn't find my answer. I need when a user types or copies any number in TextBox then the number should follow the bellow rules:

  1. Only one decimal point should be permitted.
  2. Thousand Separator.
  3. Trailing zeros should be removed. I mean the zeros after decimal point should NOT be displayed.

Update For example,

123 => 123

1234.00 => 1,234

123456.05 => 123,456.05

123456.50 => 123,456.5

How can I do this?

Mohsen
  • 971
  • 2
  • 11
  • 29
  • Hmya, why don't you just assume that a human is capable of typing a number. The vast majority of the world population knows how to do that. Treat them with respect and they'll return the favor. Only check *after* he entered it, using the Validating event. – Hans Passant Mar 16 '16 at 11:37
  • Can you be clear as to *exactly* what format? Give an example of precisely what it should look like. For example, you say 'Thousand Separator', but which one? a comma? – sr28 Mar 16 '16 at 11:37
  • 2
    You might also try a MaskedTextBox, I think it was meant for limiting user input. https://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx – GER Mar 16 '16 at 11:39
  • I updated my question and gave some examples. – Mohsen Mar 16 '16 at 11:44
  • Why do you need this? If you need to store it somewhere then so long as you can parse the text to a decimal you can do whatever formatting you like. – sr28 Mar 16 '16 at 11:46
  • @GER - make that an answer! I think `MaskedTextBox` sounds like exactly what the OP wants. – AAT Mar 16 '16 at 11:46
  • If you simply need client side validation that their input is a number then this should help: http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric – sr28 Mar 16 '16 at 11:50

1 Answers1

4

The easiest way would be to try to parse value as a number.

decimal value;
if(decimal.TryParse(textBox.Text, out value)
{
   //value is ok
   textBox.Text = string.Format("{0}", value);//If you want some fancier formatting
}
else
{
    //Value is not valid
}
Paweł Mach
  • 705
  • 1
  • 11
  • 23
  • 2
    It would be better to use `decmial`, otherwise some entries would get changed to slightly different numbers since `double` cannot exactly store all decimal numbers. – juharr Mar 16 '16 at 11:39
  • How should I format it so that it be displayed as I need? – Mohsen Mar 16 '16 at 11:54
  • @MohsenJafari Change a "string.Format" to this one: https://msdn.microsoft.com/pl-pl/library/dn906224(v=vs.110).aspx Juharr: fixed. – Paweł Mach Mar 16 '16 at 12:49