簡體   English   中英

有沒有一種方法可以將轉換為浮點數的String與實際的浮點值比較為if語句?

[英]Is there a way to compare a String converted into a float with an actual float value into an if-statement?

驗證按鈕時,我將String值轉換為浮點數,但是當我嘗試將轉換后的值與實際的浮點數進行比較時,出現編譯錯誤。 如果不想在應用程序中寫入小於50的值,我想在此進行比較。

private void tbBid_Validating(object sender, CancelEventArgs e)
        {
            var amount = 12345678.0f;
            tbBid.Text = amount.ToString();
            if(amount.ToString()<50)
            {
                e.Cancel = true;

                epbid.SetError(tbBid,">50 lei");
            }

        }

嘗試這個

//Reading value from text box
var amount = tbBid.Text;
//Parsing to float
float amountFloat = float.Parse(amount);

//Comparison
if (amountFloat < 50.0f)
{
      // Do your cancellation stuff
}

我對此做了一個簡化版,可能會對您有所幫助。 我使用了您提供的代碼和一個版本,其中amount首先是一個字符串值:

    // current example simplified
    float amount = 12345678.0f;
    string text = amount.ToString();
    if(amount < 50)
    {
        Console.WriteLine("Congratulations the first comparison worked!");
    }

    //if amount was a string to start with
    string amountText = "12345678.0";       
    float amountFloat;
    float.TryParse(amountText, out amountFloat);
    if(amountFloat < 50)
    {
        Console.WriteLine("Congratulations the second comparison worked!");
    }

這是.Net小提琴: https : //dotnetfiddle.net/utyWUc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM