How to convert input from a TextBox into a decimal

2019-08-14 20:48发布

问题:

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.

回答1:

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.



回答2:

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