0

I am currently attempting:

if (4.750 % 0.125 == 0 )

but it looks like c# doesn't want decimal for mod operation. How do I check if a number is a multiple of 0.125 then?

thanks!

Hamza
  • 17
  • 2
  • 4
    That might be tricky to check, see https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Progman Feb 19 '20 at 21:19
  • 3
    well.. you can multiply both sides with 1000 :) – Jawad Feb 19 '20 at 21:24
  • 1
    *"it looks like c# doesn't want decimal for mod operation"* what do you mean by this? Are you getting an error? If so, what is it? Also, those are `double`, not `decimal` types - add an `m` after the numbers to force them to `decimal`). – Rufus L Feb 19 '20 at 21:26
  • Possibly use plain division and see whether the result is (nearly) an integer? The trick would be to define that "nearly" – Hans Kesting Feb 19 '20 at 21:27
  • I would find a way to make them integers, so in this case multiple each side by 1000 so it would be 4750 % 125 – Yoosh Feb 19 '20 at 21:28
  • 1
    Code in the question compiles and runs fine producing expected "true" as result. Please review your question and make sure to show [MCVE] as well write exact errors/unexpected behavior you observe. Make sure to check MSDN and https://stackoverflow.com/questions/20671518/how-does-modulus-operation-works-with-float-data-type and [edit] your post with all necessary details as well as how it does not work for you. – Alexei Levenkov Feb 19 '20 at 21:31
  • If you're worried about floating-point rounding errors (i.e. you need precise values for comparison or other mathematic operations), use `decimal` instead of `double`. – Rufus L Feb 19 '20 at 21:35

2 Answers2

1

Comparing floats/doubles with zero is pretty dangerous, because of the floating-point precision. You can do two things:

  • multiply both numbers by 1000 (on example), then cast to int and do your comparison

or

  • compare like this:
if (Math.Abs(a % b) < 0.001)
Tearth
  • 286
  • 2
  • 8
  • Why not just use `decimal` instead of `double`? – Rufus L Feb 19 '20 at 21:32
  • Yeah, then everything should be ok with `a % b == 0`. But OP is saying about doubles so I gave the solution for this type (maybe he had to use them instead of decimals). – Tearth Feb 19 '20 at 21:37
1

What you could do is create a custom function to find the mod of any decimals for you:

static double DecimalMod(double a, double b) {
        if (a < b) {
            return a;
        }

        return DecimalMod(a - b, b);
}

And since comparing doubles will be annoying with floating-point precision, you'll want to use the bounds checking of:

if (Mathf.Abs(DecimalMod(4.750, 0.125)) < 0.01) {
     // Do Stuff
}```