User007 User007 - 1 year ago 85
C# Question

How to validate decimal places

Please let me know good way to validate decimal value, if decimal(4,2) it should accept 2 numeric and 2 decimal places.

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

Then finding the length will can be used, I need a better culture specific way. I need a generic solution which can be applied to all decimal field.


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

Need a generic cleaner solution for this

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;

Answer Source

You can try like this:

[RegularExpression(@"^\d{1,2}(\.\d{0,2})$",ErrorMessage = "Value contains more than 2 decimal places")]
public decimal Value { get; set; }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download