簡體   English   中英

如何驗證小數位

[英]How to validate decimal places

請讓我知道驗證小數點值的好方法,如果小數點(4,2)應該接受2個數字和2個小數位。

var value = "44.29";
var dec = value.Split('.');

然后找到可以使用的長度,我需要一種更好的文化特定方式。 我需要可以應用於所有十進制字段的通用解決方案。

喜歡:

validate(int before,int afterdecimal);
var valid  = validate(2,2);

為此需要通用的清潔劑解決方案

private static bool IsDecimal(string value, int before, int after)
{
    if (value.Contains("."))
    {
        var parts = value.Split('.');

        if (parts[0].Length == before && parts[1].Length == after)
            return true;
    }
    else if(value.Length == before)
        return false;
    return true;
}

您可以這樣嘗試:

[RegularExpression(@"^\d{1,2}(\.\d{0,2})$",ErrorMessage = "Value contains more than 2 decimal places")]
public decimal Value { get; set; }

如果您只是想驗證,請嘗試使用mod:

44.29 % 1 = 0.29

從上面的答案,我能夠做到這一點

         string value = "2009.99";
         if (IsDecimal(value, 4, 4))
         { 
            Console.WriteLine("Valid");
         }

    private static bool IsDecimal(string value, int before, int after)
    {
        var r = new Regex(@"^\d{1," + before + @"}(\.\d{0," + after + @"})$");
        return r.IsMatch(value);
    }

暫無
暫無

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

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