Modulo returns negative when mathematically it shouldn't

1 sentence description of the problem: Modulo returns negative even if mathematically it shouldn’t

Steps to reproduce the problem every time, starting in a blank draft: `Set Text to [-27%360]` or any negative value modulo positive value

I expected this to happen: not negative (returns 333 in the project)

But instead this happened: negative (returns -27)

Screenshots/video:
https://explore.gethopscotch.com/p/12rp12eg0u

Device type, player version & Hopscotch version:
→ iPhone 6s, iOS 14.x, Hopscotch newest version
→ iPhone 12, iOs 15, Hopscotch newest version

11 Likes

mathematically -27\%360=333, not -27.

7 Likes

I was wondering why some of my code wasn’t working. This has been a problem for a while.

7 Likes

yea, same here. my workaround is `(x%y + y)%y` (this returns 333 instead of the -27 bug), however one of my code did not work and i reapplied the same thing again (+y%y) which forces it to not give a negative value. it’s super annoying and some people (such as me) will wrongly understand how the modulo operator works

it was a few months ago, when i received this fx9750III graphics 3, that i understood in the hard way that all these years of coding with modulo operator was a lie, and a negative modulo will not output something negative.

7 Likes

In that case you would have to do a new rule with a check if else or two new rules:

`When (thing) < (minimim) && When (thing) > (maximum)`

``` And then a check if else that acts respectively to either.```
1 Like

(-27 % 360) returns -27 in JavaScript, which is why it returned -27 in our code. So if anything, it’s a bug in the JavaScript language, not just the app.

Main reason is because % is not a modulo operation, it’s a remainder operation. There is no actual modulo operator in JavaScript…

`(((x%y)+y)%y)` is the actual solution to the way JavaScript behaves. Your way works too.

“The JavaScript %(modulo) behaves like a remainder operation and gives the remainder and as the number is negative therefore remainder also comes out to be negative.” ~ Google

So yeah, believe it or not, this is actually intentional, according to how JavaScript works…

3 Likes