繁体   English   中英

在C#中解析十进制数

[英]Parsing a decimal number in c#

我正在尝试用一种方法解析十进制数,但是它一直给我一个运行时错误,我不明白为什么。 我必须计算对象的最终速度,但是每次尝试输入十进制数作为值时,它都会给我一个运行时错误,重点是解析十进制的位置。

private static decimal GetVelocity()
    {
        Console.Write("Please enter the intial velocity of the object: ");
        decimal mVelocity = decimal.Parse(Console.ReadLine());
        return mVelocity;
    }

有人可以告诉我我在做什么错吗?

十进制。 decimal.Parse需要有效的十进制,否则将引发错误。 1.51 ,和100.252在大多数情况下使用默认文化的所有有效小数。 您使用的区域性可能正在尝试使用不正确的分隔符(如, )来转换小数。 请参阅有关如何使用重载decimal.TryParse MSDN这篇文章 decimal.TryParse提供特定于区域性的信息。

理想情况下,应使用decimal.TryParse尝试对其进行转换,否则显示错误:

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

如果输入格式无效,则Parse将引发异常。 您2个选项。

将调用包装在try / catch块中进行解析

decimal mVelocity;

try {
    mVelocity = decimal.Parse(Console.ReadLine());
}
catch(Exception e){}

或改用TryParse

decimal mVelocity;
bool success = Decimal.TryParse(value, out mVelocity)

您的代码正在抛出异常,因为输入无法解析为十进制。 有关示例,请参见msdn

您好,您可以改用正则表达式。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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