0

Seems simple, but can't find an elegant way... I want to check if a value is within a certain range, but also is using a valid increment/resolution. Say my range is 0.1 to 99.9, with a resolution of .1. Valid values would be 1.1 and 1.2, but 1.15 is not valid. How would I check that?

6 Answers6

1

You can use the % operator:

float i = 1.15;
Console.WriteLine((decimal)i % .1M == 0);

Output: false

float i = 1.1;
Console.WriteLine((decimal)i % .1M == 0);

Output: true

D'Arcy Rittich
  • 167,292
  • 40
  • 290
  • 283
  • What if there are multiple decimals? This won't work in general. – Tudor Sep 04 '12 at 15:24
  • @Tim Croydon: It only works to test if the number has more than one decimal, but what if all values in the domain (both correct and incorrect) have at least 2 decimals? – Tudor Sep 04 '12 at 15:26
  • @Tudor If two decimal were valid (not in this case according to OP), you would use `.01` instead of `.1`. – D'Arcy Rittich Sep 04 '12 at 15:30
  • @RedFilter: I suppose that's just an example and the OP can have any decimal "resolution". – Tudor Sep 04 '12 at 15:32
  • Updated for `float` data type specified in subsequent comment. – D'Arcy Rittich Sep 04 '12 at 15:35
  • Thanks guys. This did the trick, although I had to cast my double as decimal. Doing that operation on doubles doesn't work. But no big deal for me! – user1646235 Sep 04 '12 at 15:41
0

Try something like this (for 0.1 resolution):

(x * 10) % 1 == 0
Tim Croydon
  • 1,866
  • 1
  • 19
  • 30
0

Please try:

        double a = 0.1;
        double b = 99.9;
        double x = 1.5;
        double range = 0.5;
        double epsilon = 0.000001;

        bool isRange = (x >= a) && (x <= b) && (Math.Abs((x - a)%range) < epsilon);

Here epsilon is some very small 'mistake' value

petro.sidlovskyy
  • 5,075
  • 1
  • 25
  • 29
0

You are dealing with arithmetic progression. In your example a[1] = 0.1, d = 0.1, a[999] = 99.9. If your number x is the nth member of the progression then the following holds:

n = (x - a[1])/d + 1

So you have to check whether

(x - a[1])/d

is a nonegative integer. For example:

(1.1 - 0.1)/0.1 = 10

therefore 1.1 is a member of progression. However:

(1.15 - 0.1)/0.1 = 10.5

therefore 1.15 is not a member of progression.

Andrei
  • 55,890
  • 9
  • 87
  • 108
0

Try with this code

decimal yourDecimal = ;

if( yourDecimal % .1M == 0 )
{
    ......
}
Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51
0

Consider using Math.Round to force it to the precision you want. What's the difference between 1.999 and 1.2 in your application? (See also this SO question)

Community
  • 1
  • 1
Dan Pichelman
  • 2,312
  • 2
  • 31
  • 42