问题
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