簡體   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