What does % do in JavaScript? - javascript

What does the % do in JavaScript?
A definition of what it is and what it does would be much appreciated.

It's a modulo operator. See this documentation or the specification for more information on JavaScript arithmetic operators.
% (Modulus)
The modulus operator is used as follows:
var1 % var2
The modulus operator returns the first operand modulo the second
operand, that is, var1 modulo var2, in the preceding statement, where
var1 and var2 are variables. The modulo function is the integer
remainder of dividing var1 by var2. For example, 12 % 5 returns 2. The
result will have the same sign as var1; that is, −1 % 2 returns −1.

ES6 Update:
As explained in other answers, it returns the remainder after dividing the dividend by divisor, however this is no longer modulo operator, this is remainder operator. the difference being that the modulo operator result would take the sign of the divisor, not the dividend.Quoted from MDN
The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend, not the divisor. It uses a built-in modulo function to produce the result, which is the integer remainder of dividing var1 by var2 — for example — var1 modulo var2. There is a proposal to get an actual modulo operator in a future version of ECMAScript, the difference being that the modulo operator result would take the sign of the divisor, not the dividend.
Example:
-10 % 3 // -1
10 % -3 // 1

It returns the remainder of a division operation. 5%2 returns 1

It is a modulo operator.
It calculates the remainder.
If we do 23 % 10,
first, we divide 23 by 10 which equals 2.3
then take .3 * (the divisor) 10
= 3

That would be the modulo operator.
It returns the remainder of a division operation:
var remainder = 3 % 2; // equals 1

In JavaScript, % is a remainder operator (Not a modulo operator).
remainder operator % (uses Math.truc()):
remainder = -5 % 3 = -2
How is it calculated ?
quotient = Math.trunc(dividend / divisor) = Math.trunc(-5 / 3) = -1;
remainder = dividend - divisor * quotient = -5 - (3 * -1) = -2
modulo function (uses Math.floor()):
modulo(-5,3) = 1
How is it calculated ?
quotient = Math.floor(dividend / divisor) = Math.floor(-5 / 3) = -2;
remainder = dividend - divisor * quotient = -5 - (3 * -2) = 1
For positive numbers, both remainder operator and modulo gives the same result.
5 % 3 = 2
modulo(5,3) = 2
In JavaScript, there is no build-in function for doing modulo operation, so you need to write on your own by using Math.floor() as above. Alternatively even you could easily write using the remainder operator as shown below.
function modulo(n, m) {
return ((n % m) + m) % m;
}

Just in case, if someone is looking for a real modulo function (which would always get the sign of the divisor), you can use this:
function Modulo(num, denom)
{
if (num%denom >= 0)
{
return Math.abs(num%denom);
}
else
{
return num%denom + denom;
}
}
The Math.abs is to prevent the case -12%12 → -0, which is considered equal to 0 but displayed as -0.

Modulus (%) operator returns the remainder.
If either value is a string, an attempt is made to convert the string to a number.
alert(5%3) will alert 2

% performs as the modulo operator, return division reminder. Example:
<script>
var x = 5;
var y = 2;
var z = x % y;
alert(z);
</script>
This will alert 1.

This is what I would do to getModulus, given k > 0. I find it more intuitive as Math.floor(num / k ) in js is exactly num // k in python.
function getModulus(num, k) {
return num - Math.floor(num / k ) * k
}

Related

Rounding of negative numbers in Javascript

We have come across a problem with Math.round() in JavaScript. The problem is that this function doesn't round correctly for negative numbers. For example :
1.5 ~= 2
0.5 ~= 1
-0.5 ~= 0 // Wrong
-1.5 ~= -1 // Wrong
And this is not correct according to arithmetic rounding. The correct numbers for -0.5 should be -1 and -1.5 should be -2.
Is there any standard way, to correctly round negative numbers in Javascript ?
Apply Math.round after converting to a positive number and finally roll back the sign. Where you can use Math.sign method to get the sign from the number and Math.abs to get the absolute of the number.
console.log(
Math.sign(num) * Math.round(Math.sign(num) * num),
// or
Math.sign(num) * Math.round(Math.abs(num))
)
var nums = [-0.5, 1.5, 3, 3.6, -4.8, -1.3];
nums.forEach(function(num) {
console.log(
Math.sign(num) * Math.round(Math.sign(num) * num),
Math.sign(num) * Math.round(Math.abs(num))
)
});
You could save the sign and apply later, in ES5;
function round(v) {
return (v >= 0 || -1) * Math.round(Math.abs(v));
}
console.log(round(1.5)); // 2
console.log(round(0.5)); // 1
console.log(round(-1.5)); // -2
console.log(round(-0.5)); // -1
You could try using Math.ceil(num) to round num and then - 1 if num was negative, e.g.
if (num < 0) {
num = Math.ceil(num) - 1;
} else {
num = Math.ceil(num);
}
ES6 has added a method called Math.trunc using which we can get the integer part of a decimal number
The Math.trunc() function returns the integer part of a number by
removing any fractional digits.
Math.trunc(42.84) -> Returns 42
Math.trunc(5.3) -> Returns 5
Math.trunc(-4.3) -> Returns -4
Math.trunc(-3.123) -> Returns -3
var r = (Math.random() * 200) - 100;
How about purely evaluating the result without using the math library? eg, by using a ternary operator, you can elegantly check for negative numbers and then floor after "rounding":
var n = r + (r < 0 ? -0.5 : 0.5) | 0;
The | 0 is just a silly trick in js that "overloads" the binary operator (you could use any binary operator) in order to truncate the number.
Note that this is not flooring (like Math.floor), since Math.floor(-3.2), for example, will actually yield -4.
One could even do something similar to #Balan's answer (I like that one and the one below, but I feel like this or the ternary operator will just be a touch faster--I am probably wrong, though, because the Math libraries have been proven to be very fast):
var n = (r + Math.sign(r) / 2) | 0;
probably the fastest, most elegant way:
var n = Math.floor(r + 0.5);
example:
var body = document.getElementById("myTable").children[1];
var i, iMax = 100, r, tr, td;
for (i = 0; i < iMax; i++) {
r = Math.random() * 200 - 100;
tr = document.createElement("tr");
td = document.createElement("td");
td.innerHTML = r;
tr.appendChild(td);
td = document.createElement("td");
td.innerHTML = (r + Math.sign(r) / 2) | 0;
tr.appendChild(td);
body.appendChild(tr);
}
#myTable {
min-width: 250px;
}
<table id="myTable">
<thead>
<tr>
<th>float</th>
<th>round</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Rounding with precision.
Rounds to Int by default or, if second argument is provided, to n digits after decimal point.
+ '1' fixes incorrect rounding for .0X5 numbers.
function round(num, digits=0) {
if (!(num % 1)) return num
return +Number(num + '1').toFixed(digits)
}
First observe that Math.round(v) is defined as Math.floor(v + 0.5):
Math.round(-1.7) === -2
Math.round(-1.3) === -1
Math.floor(-1.7 + 0.5) === -2
Math.floor(-1.3 + 0.5) === -1
Then realize that parseInt(v) is similar to Math.floor(v), however, it handles negative numbers differently (exactly how you expected it to behave):
Math.floor(1.7) === 1
Math.floor(-1.7) === -2
parseInt(1.7) === 1
parseInt(-1.7) === -1
So the parseInt(v) behavior is what you want, but instead of flooring, you want rounding. In order to apply this to any number, we need to add +0.5 for positive numbers, and -0.5 for negative numbers. So the solution is this function:
var parseIntRound = function(v)
{
return parseInt(v + Math.sign(v)/2);
};
// or with modern syntactic sugar:
// const parseIntRound = v => parseInt(v + Math.sign(v)/2);
parseIntRound( 1.5) === 2
parseIntRound( 0.5) === 1
parseIntRound(-0.5) === -1
parseIntRound(-1.3) === -1
parseIntRound(-1.5) === -2
parseIntRound(-1.7) === -2
Where Math.sign(v) returns 1 for any positive number (>0), -1 for any negative number (<0), and 0 for positive zero (and -0 for negative zero).

What does the zero refer to in the code below

I know this is a very basic question but what does the 0 refer to in the code below
var even = arr.filter(function(val) {
return 0 == val % 2;
});
what does the 0 refer to
Here 0 refers to the Number 0.
0 == val % 2
will evaluate to true or false which you are returning.
0 is the tested value of val modulus (%) 2. When there is no "remainder", as with even numbers, it will return the number 0. For odd numbers it will have a remainder of 1 and the function will return false to filter().
The % is the modulus operator, it works like this
The remainder operator (modulus) returns the first operand modulo the
second operand, that is, var1 modulo var2. The modulo function
is the integer remainder of dividing var1 by var2
MDN
In other words, if val can be divided by 2, the modulus operator returns 0 as there is no remainder, that's why it checks for a zero
Turning the yoda condition around, it makes more sense
val % 2 === 0; // can be divided by 2, so it's even, returns boolean
For instance if val was 4, 16, 200 etc, it would be true, as 4 can be evenly divided by 2.
If val was 3, 9, 201 etc. it would be false, as 3 can not be evenly divided by 2.
0 is just a number which is compared to right hand side expression val % 2
statement 0 == val % 2; returns true if val % 2 is 0 (value of val is even), or returns false is val % 2 is 1 (value of val is odd)
Just for information: Modulo operator returns the remainder(a number) when val is divided by any number

How does JavaScript handle modulo?

I was wondering how JavaScript handles modulo. For example, what would JavaScript evaluate 47 % 8 as? I can’t seem to find any documentation on it, and my skills on modulo aren’t the best.
Exactly as every language handles modulo: The remainder of X / Y.
47 % 8 == 7
Also if you use a browser like Firefox + Firebug, Safari, Chrome, or even IE8+ you could test such an operation as quickly as hitting F12.
Javascript's modulo operator returns a negative number when given a negative number as input (on the left side).
14 % 5 // 4
15 % 5 // 0
-15 % 5 // -0
-14 % 5 // -4
(Note: negative zero is a distinct value in JavaScript and other languages with IEEE floats, but -0 === 0 so you usually don't have to worry about it.)
If you want a number that is always between 0 and a positive number that you specify, you can define a function like so:
function mod(n, m) {
return ((n % m) + m) % m;
}
mod(14, 5) // 4
mod(15, 5) // 4
mod(-15, 5) // 0
mod(-14, 5) // 1
Modulo should behave like you expect. I expect.
47 % 8 == 7
Fiddle Link
TO better understand modulo here is how its built;
function modulo(num1, num2) {
if (typeof num1 != "number" || typeof num2 != "number"){
return NaN
}
var num1isneg=false
if (num1.toString().includes("-")){
num1isneg=true
}
num1=parseFloat(num1.toString().replace("-",""))
var leftover =parseFloat( ( parseFloat(num1/num2) - parseInt(num1/num2)) *num2)
console.log(leftover)
if (num1isneg){
var z = leftover.toString().split("")
z= ["-", ...z]
leftover = parseFloat(z.join(""))
}
return leftover
}

Understanding this Javascript code using % modulus

Im currently in process of learning Javascript. And I have seen the following code, which confuses me.
Description of code:
Starting on line 1, the function isOdd takes a number n and returns a boolean (true or false) stating whether the number is odd or not.
Code
var isOdd = function (n) {
if (n % 2 === 0) {
return false;
} else {
return true;
}
};
var isEven = function(n) {
if(n % 2 === 0) {
return true;
} else {
return false;
}
};
Where I am confused.
The code:
n % 2 === 0
I have always taken the following to be the description for %:
% Is the modulus operator. It returns the remainder of dividing number1 by number2.
Which would mean that the if statement in the function isOdd returns false is the difference between n and 2 is 0. But its meant to mean if n is divisible by 2 (even) return false.
I just dont see how its doing that.
In my mind, if we take the even number 30. Apply it to n % 2. We get 15, which is remainder of dividing 30 by 2. 15 does not equal 0, but 30 is an even number, and with this code it would be seen as odd.
Can someone explain this?
The line in question:
if (n % 2 === 0) {
return false;
}
Means "if when you divide n by 2 the remainder is zero, then return false (i.e. n is not odd)".
The "remainder" is whatever is left over when you subtract the nearest multiple, so for example "64 % 10" is 4, since the nearest multiple of 10 is 60, leaving 4.
Taking your example and putting it another way, 30/2 is 15, 30%2 is zero (i.e. whatever is left over after 30/2). Here's more info on the remainder after division.
You're confusing Quotient and Remainder.
When you divide 30 by 2, integer quotient is 15, and remainder is 0. You can also calculate remainder by multiplying integer quotient by divisor and subtracting it from dividend. So for this division remainder is 30 (dividend) - 15 (quotient) * 2 (divisor) = 0.
If n can be divided by 2 it means it's even ->
which means it's not odd ->
isOdd is false

how to convert -1 to 1 with javascript?

how to convert -1 to 1 with javascript ?
var count = -1; //or any other number -2 -3 -4 -5 ...
or
var count = 1; //or any other number 2 3 4 5 ...
result should be
var count = 1; //or any other number 2 3 4 5 ...
count = Math.abs(count)
// will give you the positive value of any negative number
The abs function turns all numbers positive: i.e Math.abs( -1 ) = 1
Alternative approach (might be faster then Math.abs, untested):
count = -5;
alert((count ^ (count >> 31)) - (count >> 31));
Note that bitwise operations in javascript are always in 32-bit.
If the number of interest is input... In addition to Math.abs(input)....
var count = (input < 0 ? -input : input);
jsFiddle example
(edit: as Some pointed out -input is faster than -1 * input)
The above makes use of the Javascript conditional operator. This is the only ternary (taking three operands) Javascript operator.
The syntax is:
condition ? expr1 : expr2
If the condition is true, expr1 is evaluated, if it's fales expr2 is evaluated.

Categories

Resources