Reputation: 1
I'm trying to parse a decimal number in one of my methods, but it keeps giving me a runtime error and I don't understand why. I have to calculate the final velocity of an object, but every time I try to enter a decimal number as a value, it gives me a runtime error, focusing on where I parsed the decimal.
private static decimal GetVelocity()
{
Console.Write("Please enter the intial velocity of the object: ");
decimal mVelocity = decimal.Parse(Console.ReadLine());
return mVelocity;
}
Can someone please tell me what I'm doing wrong?
Upvotes: 0
Views: 949
Reputation: 393
Hi You can use regex instead.
private static decimal GetVelocity()
{
Regex regex = new Regex(@"^[0-9]([.,][0-9]{1,3})?$");
Console.Write("Please enter the intial velocity of the object: ");
string decimalInput = Console.ReadLine();
while (!regex.IsMatch(decimalInput))
{
Console.WriteLine("Wrong input");
decimalInput = Console.ReadLine();
}
decimal mVelocity = decimal.Parse(decimalInput);
return mVelocity;
}
Upvotes: -1
Reputation: 22911
decimal.Parse
needs a valid decimal, otherwise it will throw an error. 1.5
, 1
, and 100.252
are all valid decimals in most cases with the default culture. The culture you're using may be attempting to convert a decimal using an incorrect separator (Like ,
). See this MSDN article on how to use the overloaded decimal.TryParse
to provide culture specific information.
Ideally, you should use decimal.TryParse
to attempt to convert it, and display an error otherwise:
private static decimal GetVelocity()
{
Console.WriteLine("Please enter the intial velocity of the object: ");
decimal mVelocity;
while ( !decimal.TryParse(Console.ReadLine(), out mVelocity) )
{
Console.WriteLine("Invalid velocity. Please try again: ");
}
return mVelocity;
}
Upvotes: 2
Reputation: 8986
If the input is in an invalid format Parse
will throw an exception. You 2 options.
Wrap the call to parse in a try/catch block
decimal mVelocity;
try {
mVelocity = decimal.Parse(Console.ReadLine());
}
catch(Exception e){}
Or use TryParse
instead.
decimal mVelocity;
bool success = Decimal.TryParse(value, out mVelocity)
You're code is throwing an exception because the input cannot be parsed to a decimal. See msdn for examples
Upvotes: 0