1

Trying to get the modulo operator to work in javascript. This is for a NodeRed function that takes in values in a array. I can get the avg value out without the modulo operator, with it nothing happens. Can anyone help? The point of this is to get the avg angles correct considering 0-360 degrees

value1 = {};
value2 = {};
value3 = {};
value4 = {};
value5 = {};
avg = {};


msg.number = msg.payload;

value1.payload=msg.number[1];

value2.payload=msg.number[2];

value3.payload=msg.number[3];

value4.payload=msg.number[4];

avg.payload = (((msg.number[1]+msg.number[2]+msg.number[3]+msg.number[4])/4)%360);


return avg;
2
  • **%360** What is this expected to do? You may get more insight as to what's breaking if you look at the console. Commented Feb 3, 2017 at 14:34
  • are the ** before and after %360 there for emphasis or is it the actual code? Also, please give examples of the input data: msg.number[1] is actually a number? what's the value range? Commented Feb 3, 2017 at 14:37

1 Answer 1

1

The module operator returns the remainder of division between two operands. It seems like you want the average angle which would be your function:

((msg.number[1]+msg.number[2]+msg.number[3]+msg.number[4])/4)

If you do still want to apply modulo of 360 to this, you should remove the surrounding ** ** and have this:

avg.payload = ((msg.number[1]+msg.number[2]+msg.number[3]+msg.number[4])/4) % 360;

But by adding '% 360' you are returning the average of the angles since they in theory will not be greater than 360. If you want the remainder of the angles compared to 360 you could try this:

avg.payload = 360 % ((msg.number[1]+msg.number[2]+msg.number[3]+msg.number[4])/4);

and see if that gets you the result you wanted.

If you want more info on the operator I'd review Mozilla's JavaScript:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.