简体   繁体   English

在C#中解析十进制数

[英]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. 十进制。 decimal.Parse需要有效的十进制,否则将引发错误。 1.5 , 1 , and 100.252 are all valid decimals in most cases with the default culture. 1.51 ,和100.252在大多数情况下使用默认文化的所有有效小数。 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. 请参阅有关如何使用重载decimal.TryParse MSDN这篇文章 decimal.TryParse提供特定于区域性的信息。

Ideally, you should use decimal.TryParse to attempt to convert it, and display an error otherwise: 理想情况下,应使用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;
}

If the input is in an invalid format Parse will throw an exception. 如果输入格式无效,则Parse将引发异常。 You 2 options. 您2个选项。

Wrap the call to parse in a try/catch block 将调用包装在try / catch块中进行解析

decimal mVelocity;

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

Or use TryParse instead. 或改用TryParse

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 有关示例,请参见msdn

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

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

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