如何将字符串转换为int或decimal?

Bax*_*tex 2 c# decimal

我有这个代码:

Console.WriteLine("What is the price of the product?"); 
Decimal price = Decimal.Parse(Console.ReadLine());  
Run Code Online (Sandbox Code Playgroud)

我将输入作为字符串作为int或/和十进制数并将其转换为变量.或者,这是我的意图.输入是产品的价格,它可以有小数,也可以不是.我只输入整数,它可以工作,但是小数点会崩溃.我是新手,我似乎无法找到答案.

Sel*_*enç 9

使用TryParse防止异常:

while (true)
{
     string input = Console.ReadLine();
     decimal result;
     if (decimal.TryParse(input, out result))
     {
          // do your work
          break;
     }
     else
     {
          Console.WriteLine("invalid value try again");
     }
}
Run Code Online (Sandbox Code Playgroud)

我也使用while循环强制用户输入正确的值.如果你不想要它,你可以忽略循环.