2

I have a decimal field that I receive back in a controller in C# MVC. I need to know if it's value in decimal has no more than three positions.

So 0.00 is accepted as well as 0.01, but 0.001 would be denied.

Doing this:

if (discount > 1 || discount< (decimal) 0.01)
{
    // Log error
}

Only partially works since the 0.00 is denied. How could I do that?

hsim
  • 2,000
  • 6
  • 33
  • 69
  • See this question to count number of decimals: http://stackoverflow.com/questions/13477689/find-number-of-decimal-places-in-decimal-value-regardless-of-culture You could find something of interest – dee-see Dec 10 '13 at 21:53
  • @Vache That's solving a harder problem than this is. It can work, but it's more work than you need to do. – Servy Dec 10 '13 at 21:53

2 Answers2

4

Just take the remainder when dividing by the decimal by 0.01. If it's zero, then there are no values after that decimal place, if there are some, then there are:

bool hasSomethingAfterSecondDecimalDigit = discount % 0.01m != 0m;

Note that this will work as expected for negative numbers as well.

Servy
  • 202,030
  • 26
  • 332
  • 449
2

Modulo is probably a more expensive operation than just plain old integer casting:

if((int)(discount*100) != discount*100) { /* more digits than wanted */ }

Both ways are probably just as fast in practice, and it's a matter of personal preference.

Another plain and simple approach:

if(Math.Round(discount, 2) != discount) { /* too precise */ }
Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
  • 1
    This is actually going to be *more* expensive. Calculating the remainder is going to be identical to performing the division. In order to calculate the division you will have found the remainder; it's what's left after you do the division. At a low level you generally have a `DIVMOD` function of some sort that calculates both; each operation either remainder or division, just takes the value it wants and discards the other. Everything else you do, such as the multiplication, is extra effort spent. – Servy Dec 10 '13 at 21:56
  • 1
    You're referring to the previous version I corrected. It's only using multiplications now which are at FPU level certainly cheaper than divisions - I just doubt it'll be noticeable. – Niels Keurentjes Dec 10 '13 at 21:59
  • 1
    I agree it's not likely to be noticeable; I only commented because you brought it up. – Servy Dec 10 '13 at 21:59
  • 1
    Yeah well he has 3 valid solutions now, time to get nitpicky about the details :P – Niels Keurentjes Dec 10 '13 at 22:00