简体   繁体   中英

Parsing a decimal number in c#

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM