I have this in my view model:

```
[Required(ErrorMessage = "Price is required")]
[Range(0.01, 999999999, ErrorMessage = "Price must be greater than 0.00")]
[DisplayName("Price ($)")]
public decimal Price { get; set; }
```

I'd like to validate that the user doesn't enter more than 2 decimal places. So I'd like to have

**Valid values**: 12, 12.3, 12.34

**Invalid values**: 12., 12.345

Is there a way to validate this with a data annotation?

You can make this validation by using a regular expression and apply it with RegularExpression attribute.

You could use the RegularExpression attribute, with a regex that matches your criteria. There are a whole bunch of expressions here that involve numbers, I'm sure one will fit the bill: http://regexlib.com/DisplayPatterns.aspx?cattabindex=2&categoryId=3

This will get you started, though it may not be as inclusive as you want (requires at least one digit leading the decimal point):

[RegularExpression(@"\d+(.\d{1,2})?", ErrorMessage = "Invalid price"]

Note that it is difficult to emit a precise error message because you don't know which part of the regex failed to match (the string "z.22" has the correct number of decimal places, for example, but is not a valid price).

```
[RegularExpression(@"^\d+(\.\d)?$", ErrorMessage = "It cannot have more than one decimal point value")]
[Range( 0.1,100)]
public double xyz{get;set;}
```

It works for me upto one decimal value

```
[RegularExpression(@"^\d+.\d{0,2}$",ErrorMessage = "Price must can't have more than 2 decimal places")]
public decimal Price { get; set; }
```

This will cater for 0 to 2 decimal places, or none at all.

You can also create your own Decimal validation attribute, inheriting from RegularExpressionAttribute:

```
public class DecimalAttribute : RegularExpressionAttribute
{
public int DecimalPlaces { get; set; }
public DecimalAttribute(int decimalPlaces)
: base(string.Format(@"^\d*\.?\d{{0,{0}}}$", decimalPlaces))
{
DecimalPlaces = decimalPlaces;
}
public override string FormatErrorMessage(string name)
{
return string.Format("This number can have maximum {0} decimal places", DecimalPlaces);
}
}
```

and register it to enable client-side validation in Application_Start():

```
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DecimalAttribute), typeof(RegularExpressionAttributeAdapter));
```

I had the same scenario as the OP, yet the answers provided don't give a solution that works for all of the following cases:

`12, 12.3 and 12.34`

To do that, we use the following regular expression:

```
[RegularExpression(@"^\d+(.\d{1,2})?$")]
```

Similar to **mattytommo**. You need to escape '.' - otherwise ANY character will be accepted

```
[RegularExpression(@"^\d+(\.\d{1,2})?$")]
```

Similar Questions

I want a regular expression for decimal input, which can take 4 digits before decimal or comma and 2 digits after decimal/comma. 5 digit number without decimal is invalid. Also can accept null. Correc

I need to convert minutes to hours, rounded off to 2 decimal places.I also need to display only up to 2 numbers after the decimal point. So if I have minutes as 650.Then hours should be 10.83 Here's w

It always returns biggest decimal places value. In following example it always returns 4 decimal places. SELECT CASE WHEN 1 = 1 THEN ISNULL(CAST(1000 AS FLOAT), -1) WHEN 1 = 2 THEN ISNULL(CAST(0.0040

I'm trying to round BigDecimal values up, to two decimal places. I'm using BigDecimal rounded = value.round(new MathContext(2, RoundingMode.CEILING)); logger.trace(rounded {} to {}, value, rounded);

I need to display int value in minimum 2 digit before decimal in sql server. Is it possible than how pls rply?

I have a basic question. I'm not really good at programming. I'm trying to display an answer to 2 decimal places in my answer field. I have my JTextFields and my JRadioBtn set. When the answer comes f

I am using devexpress TextEditSettings in dxgrid in editsettings.. How can i restrict the user to enter value with 3 decimal places and value range should be 0-1000

Have decimal amount, want to trim to 2 decimal places if present

I have tried the following code but it is not working in a particular case. Eg: Suppose, I have a double value=2.5045 and i want it to be rounded off upto two decimal places using the below code.After

I am making a simple daily sales and expense report sheet to store on my server with inputed information. The problem I am having is the output, or the result uses the two decimal places, but it multi

Assume i have the following decimal value: 4.584406 I need a simple quick way to truncate the decimal without rounding up, so the output would be 4.5 I'm using T-SQL (SQL Server 2005/2008). Any help w

Lets say I have a value of 3.4679 and want 3.46, how can I truncate to two decimal places that without rounding up? I have tried the following but all three give me 3.47: void Main() { Console.Write(M

I want to display a number which is of double datatype in C#, in grouped digits and with two decimal places only if it contains a decimal no. e.g. If there is 2000.4567 and 2000.45, it must be display

every time I want to round to 2 decimal places when it comes to zeros it doesnt want to round it... how could I round it to 2 decimal places with zeros at the end which would give me 92.00 instead of

Firebird truncates decimal places when dividing, rather than rounding. Furthermore, it bases the number of decimal points in the returned value on the number of decimal places in the numerator and den

I'm working with MS Access to do some math. I'm taking a Cost and Dividing it by a decimal value to get a Price. I'm using a link table and a access sql query. SQL Ex Select (cost/markup) As Price Fro

How do you make it so that all calculations in the DB compute to a pre-specified # of decimal places? Say I have three tables with the following fields Table1 A int B decimal(18, 3) Table2 A int B

I have to selected some column data from a database table and make this data with two decimal places only. I see this SQL.Strings = ('select' #9'my_index '#9'his_index,'... What is that #9? How can

I have a requirement to set prices on certain items to 3 decimal places. I have achieved this by changing the 'precision' variable to 3, however this now means that every price on the site is displaye

Possible Duplicate: How do I format numbers to have only two decimal places? I have looked all over for a solution. Say i have a variable with a number like this: $price1 = 1597; $price2 = 1497.85;

I need a RegEx for a numeric value with up to two decimal places greater than zero and may or may not have a zero in the ones column. I should also add....whole numbers are fine. See somments below bu

I am using Rmd file to create a report and I used xtable package to create the table. The output of the xtable shows the number of decimal places upto 2 digits. Is there a way to control the decimal p

I have a table which contains a field of type numeric(28,10). I would like to display the records with a monospaced font, and a matching number of decimal places so that they line up when right aligne

I have the following code. I would like to have it such that if price_result equals an integer, lets say 10 then I would like to add two decimal places. So 10 would be 10.00. Or if it equals 10.6 woul

I'm trying to format a double to just 2 decimal places in Java. I've read the following post: How to round a number to n decimal places in Java For some reason, every one of those methods fails to wor

Possible Duplicate: c# - How do I round a decimal value to 2 decimal places (for output on a page) I have an XML file with decimal values of temperature in string format. Examples: <temp>30&l

This question already has an answer here: Variable interpolation inside printf-style formatting functions 2 answers In Objective-C, how do you round a number to n decimal places, when n is a va

I am trying to round to two decimal places in my code below, however, in many cases the Math Round method to control the number of decimal places does not work for me. var newKitAmount = 1; var pric

I need a function which takes a calculated value (can range from very small to very large) and rounds it to a number of decimal places for display. The number of decimal places should depend on the ma

I am trying to write a program. which round off decimal digits(23.4353353 to 23.435).it is working fine for me. Problem:- if i enter 23 only digit no decimal ,it is showing only 23.0. if decimalvalue

To place decimal plases in a text box I have use jquery.number plugin. $(# + crisisCapId).number(true, 2); After adding this plugin, if someone enter 0 i want to clear text box ( ). if (crisis

Possible Duplicate: c# - How do I round a decimal value to 2 decimal places (for output on a page) i have value of 1.564 and 1.565 i need round this value to 1.56 and 1.56,which function suitable fo

I am using the following to put decimal places when formatting an amount but I am not getting the correct amount when testing with eg 25000 I am expecting 25000.00 but I am getting 25000. What I am do

How can i round off decimal number to 2 places in Velocity Template Engine? set ($Percentage = $Marks*100/$Total) I want to round off Percentage to 2 decimal places. How can i do that? will Double ro

I was wondering how to make avg in the following program round to 3 decimal places: public class BaseballCalculator { public static void main(String args[]) { Scanner myScanner = new Scanner(System.i

This question already has an answer here: JavaScript: formatting number with exactly two decimals 12 answers I'm trying to get the following to output to 2 decimal places: $(#incP1).click(fun

I'm not able to increase the decimal places from 2 to 4 at the price-field in Magento Backend for downloadable products. Where do I have to start to find that piece of code?. Any help very appreciated

to calculate some longitude and latitude values I need more decimal places like mysql is possible to do. For instance with mysql I get this result: cos( RADIANS( 47.685618 ) ) = 0.67319814951254 With

Possible Duplicate: c# - How do I round a decimal value to 2 decimal places (for output on a page) I want to truncate the decimals like below i.e. 2.22939393 -> 2.229 2.22977777 -> 2.229

I have a decimal in .NET and I need to store it to a column in a typed dataset that is a string. I need the decimal to be stored to two decimal places. Even though I use Math.Round(value,2) and I do a

I currently have a long list of code as follows: <line fill=none x1=555 y1=562.8181152 x2=542.1015625 y2=579.6394043/> <line fill=none x1=542 y1=579.6394043 x2=527.46875 y2=

So I have this code: p.Value = 1; decimal avg = p.Value * 100 / 10000; string prntout = p.Key + : + avg.ToString(); Console.WriteLine(prntout); But the program prints out 0, instead of 0.01. p.Va

I would like to know how can I output a number with 2 decimal places, without rounding the original number. For example: 2229,999 -> 2229,99 I already tried: FORMAT(2229.999, 2) CONVERT(2229.999,

In mysql if I want to do a simple qu ery : select * from testtable where id = 192.1111 and i just want to select upto 2 decimal places, how do i go about it ? conclusion should be that the testtable

I have rounded the 'legInches' but how do I round this to 2 decimal points instead of none? specifically - (int)round(legInches) result = (isTitle)? @Leg Span : [NSString stringWithFormat:@%dcm / %

Is there a way to make a decimal variable hold decimal places always. Even if the decimal places only have 0s. E.g.: 10.00, 100.000, 1000.00, etc. I know we can do it with a string variable like st

I want to convert value into 2 decimal part in expression column of DataTable. e.g. value = 23.2546876 i want = 23.25 please help me....

I think this is a dumb question. but i cannot figure it out. Please don't shoot me. :P I want to get double value like 8.000000111333. but I can only get up to 6 decimal places. for instance double _

I am facing problem while rounding the decimal value in C# using Math.Round(a, 2); When I'm rounding 1.275 by 2 decimal points, the result is 1.27. When I'm doing the same for 1.375, the result is 1.3

I'm wondering if there is a concise and accurate way to pull out the number of decimal places in a decimal value (as an int) that will be safe to use across different culture info? For example: 19.0 s