Unexpected Negative Results in JavaScript's Modulo Operator
When using the modulo operator (%) in JavaScript for negative numbers, it can produce surprising results. For instance, (-13) % 64 in Google Calculator equals 51, while in JavaScript it returns -13.
Understanding the Issue
JavaScript's modulo operator calculates the remainder after division, but it does not apply the same logic to negative numbers as mathematical operations like Google Calculator. In JavaScript, the modulo operator returns a value with the same sign as the first operand.
Fixing the Issue
To correct this behavior and ensure consistency with mathematical operations, you can use the following custom implementation of the modulo operator:
Number.prototype.mod = function (n) { "use strict"; return ((this % n) + n) % n; };
Usage
Once the custom modulo method is defined, you can use it to calculate the remainder of negative numbers:
console.log((-13).mod(64)); // Outputs 51
This corrected behavior aligns with the expected mathematical result and ensures consistent behavior across different platforms.
The above is the detailed content of Why Does JavaScript\'s Modulo Operator Produce Unexpected Results with Negative Numbers?. For more information, please follow other related articles on the PHP Chinese website!