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

时间:2014-02-01 20:29:28

标签: c# decimal

我有这段代码:

Console.WriteLine("What is the price of the product?"); 
Decimal price = Decimal.Parse(Console.ReadLine());  

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

2 个答案:

答案 0 :(得分: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");
     }
}

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

答案 1 :(得分:0)

实现这一目标有很多方法。例如:

string Input = Console.ReadLine();
Decimal InputConvertedAsDecimal;
if (Decimal.TryParse(Input, out InputConvertedAsDecimal)
{
    Console.WriteLine("Inputted number is: " + InputConvertedAsDecimal.ToString(CultureInfo.InvariantCulture));
}
else
{
    Console.WriteLine("Error! Input have a incorrect format to parse.");
}