How to convert a string to an int or decimal?

瘦欲@ 提交于 2019-12-12 22:13:44

问题


I have this code:

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

I take a input as a string as either a int or/and decimal number and convert it to a variable. Or well, that is my intention. The input is a price of a product and it can have decimals or it cannot. I you only type in ints, it works, but with decimals it crashes. I'm new to this and I can't seem to find an answer.


回答1:


Use TryParse to prevent exception:

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");
     }
}

Also I have used while loop to force user to enter correct value.If you don't want it you can ignore the loop.




回答2:


There is many ways how achieve this. For example:

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.");
}


来源:https://stackoverflow.com/questions/21503239/how-to-convert-a-string-to-an-int-or-decimal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!