How to convert a string to an int or decimal?
c#, decimal
Solution
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.
Problem
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.