简体   繁体   English

如何将TextBox中的输入转换为十进制数

[英]How to convert input from a TextBox into a decimal number

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...) (例如:偶数/奇数,可被2/5/10整除,是素数等...)

Sadly I'm already failing at grabbing the number from the user input. 可悲的是,我已经无法从用户输入中获取数字了。

  1. I need a TextBox that only allows Numbers. 我需要一个只允许Numbers的TextBox。 (I know NumericUpDown is an option but I wanted to try it with a TextBox) (我知道NumericUpDown是一个选项,但我想用TextBox尝试)

  2. I need to convert the String from the TextBox into a float (?) (or double ?). 我需要将TextBox中的String转换为float (?)(或double ?)。 I know int won't work because I don't want it to cut all the decimal places. 我知道int不起作用,因为我不希望它削减所有小数位。

  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和2的帮助。

What are you using? 你在用什么? WPF, Windows Forms or ASP.NET? WPF,Windows窗体还是ASP.NET? As for converting it to a decimal all you have to do is parse it or use the Convert class. 至于将它转换为十进制,你所要做的就是解析它或使用Convert类。 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. 很可能你只需要将文本框的名称称为文本访问器,并将其作为参数传递给转换或解析,并将其填充到变量中。

You can use Double.TryParse or Double.Parse 您可以使用Double.TryParseDouble.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 TryParse()方法与Parse ()方法的不同之处在于,第一个返回一个布尔值,指示解析操作是否成功,而第二个返回解析后的数值(如果成功),如果失败则抛出异常

Here is a simple example: 这是一个简单的例子:

string value = Textbox1.Text;
double number;


if (Double.TryParse(value, out number))
     //The method succeeded
else
    // The method failed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM