Home >Web Front-end >JS Tutorial >Why Does JavaScript\'s Modulo Operator (%) Produce Unexpected Results with Negative Numbers?
JavaScript's % Operator for Negative Numbers: A Negative Surprise
The modulus operator (%) is a valuable tool for working with remainders. However, when it comes to negative numbers in JavaScript, the results can be unexpected.
The Problem:
In cases like (-13) % 64, JavaScript returns -13, while conventional calculators like Google Calculator give a positive result (51). This discrepancy stems from the operator's behavior with negative operands.
The Fix:
To overcome this issue, a custom implementation of the modulus operator for negative numbers can be employed:
Number.prototype.mod = function (n) { "use strict"; return ((this % n) + n) % n; };
This modification ensures that the result of (-13) % 64 is 51, aligning with the expected mathematical outcome. For more information, refer to the "The JavaScript Modulo Bug" article.
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!