Home > Web Front-end > JS Tutorial > Why Does JavaScript\'s Modulus Operator Produce Unexpected Results with Negative Numbers?

Why Does JavaScript\'s Modulus Operator Produce Unexpected Results with Negative Numbers?

Patricia Arquette
Release: 2024-11-26 02:22:12
Original
757 people have browsed it

Why Does JavaScript's Modulus Operator Produce Unexpected Results with Negative Numbers?

JavaScript's Modulus Operator Behavior for Negative Numbers

In JavaScript, the modulus operator (%) calculates the remainder of the division operation. However, it behaves differently for negative dividend values than mathematical conventions and other programming languages.

When performing a modulus operation on a negative dividend, JavaScript returns a negative remainder, while mathematical calculations and most other programming languages yield a positive one. This can be demonstrated with the following example:

  • Google Calculator: (-13) % 64 = 51 (expected result)
  • JavaScript: console.log(-13 % 64) = -13 (incorrect result)

Resolving the Issue

To obtain the correct result for modulus operations involving negative numbers in JavaScript, we can use the following custom function:

Number.prototype.mod = function (n) {
  "use strict";
  return ((this % n) + n) % n;
};
Copy after login

This function, when applied to negative dividends, ensures that the returned remainder is positive. For instance:

console.log((-13).mod(64)); // Output: 51 (correct result)
Copy after login

The above is the detailed content of Why Does JavaScript\'s Modulus Operator Produce Unexpected Results with Negative Numbers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template