1

Here is what I want to create: A program where the user can enter any decimal number and is told all the qualities of that number. (For example: even/odd, divisible by 2/5/10, is a prime number, etc...)

Sadly I'm already failing at grabbing the number from the user input.

  1. I need a TextBox that only allows Numbers. (I know NumericUpDown is an option but I wanted to try it with a TextBox)

  2. I need to convert the String from the TextBox into a float(?) (or double?). I know int won't work because I don't want it to cut all the decimal places.

  3. I need to test the number for all the qualities and then report back. (I´ll manage that).

I need help with steps 1 & 2.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Shulkster
  • 11
  • 1
  • 2
  • 5
    To save you time, it seems easier to allow the textbox to take any input, and use `var conversionOK = Decimal.TryParse(TextBox.Text, out decimalVariable)` to test if the textbox input could be converted into a decimal successfully. – Derreck Dean Oct 14 '15 at 20:08
  • 1
    You could also declare your textbox as a double to keep its precision: TextBox.double – user1789573 Oct 14 '15 at 20:09
  • Possible duplicate of [How do I make a textbox that only accepts numbers?](http://stackoverflow.com/questions/463299/how-do-i-make-a-textbox-that-only-accepts-numbers) – Heretic Monkey Oct 14 '15 at 20:25
  • @Deerreck Dean this gives me the Error "Argument 1: cannot convert from 'decimal' to 'string'" wich i dont understand. i thought this will try to convert from 'string' to 'decimal' ? And why do i get the error? – Shulkster Oct 15 '15 at 16:16
  • Nevermind, i got it to work! Thank you all! – Shulkster Oct 15 '15 at 16:25

2 Answers2

2

What are you using? WPF, Windows Forms or ASP.NET? As for converting it to a decimal all you have to do is parse it or use the Convert class. Most likely you'll just put the name of your text box call it's text accessor and pass it in to a convert or parse as a parameter and stuff it into a variable.

General Charismo
  • 123
  • 1
  • 1
  • 10
1

You can use Double.TryParse or Double.Parse

The TryParse() method differs from the Parse() method is that the first returns a Boolean value that indicates whether the parse operation succeeded while the second return the parsed numeric value if succeeded, and throws an exception if it fails

Here is a simple example:

string value = Textbox1.Text;
double number;


if (Double.TryParse(value, out number))
     //The method succeeded
else
    // The method failed
S.Dav
  • 2,436
  • 16
  • 22