Javascript Arithmetic
Constants
Constants | Description | Approximate |
---|---|---|
Math.E | Base of natural logarithm e | 2.718 |
Math.LN10 | Natural logarithm of 10 | 2.302 |
Math.LN2 | Natural logarithm of 2 | 0.693 |
Math.PI | Pi: the ratio of circle circumference to diameter (π) | 3.14 |
Math.SQRT1_2 | Square root of 1/2 | 0.707 |
Math.SQRT2 | Square root of 2 | 1.414 |
Number.MAX_VALUE | Largest positive finite value of Number | 1.79E+308 |
Number.MIN_VALUE | Smallest positive value for Number | 5E-324 |
Infinity | Value of positive infinity (∞) | 0--- |
Remainder / Modulus (%)
The remainder / modulus operator (%) returns the remainder after (integer) division.
console.log( 42 % 10);
console.log( 42 % -10);
console.log(-42 % 10);
console.log(-42 % -10);
console.log(-40 % 10);
console.log( 40 % 10);
Output
2
-2
-2
-0
0
This operator returns the remainder left over when one operand is divided by a second operand. When the first operand is a negative value, the return value will always be negative, and vice versa for positive values.
In the example above, 10 can be subtracted four times from 42 before there is not enough left to subtract again without it changing sign. The remainder is thus: 42 - 4 * 10 = 2.
The remainder operator may be useful for the following problems:
Rounding
Math.round() will round the value to the closest integer using half round up to break ties.
var a = Math.round(2.3);
var b = Math.round(2.7);
var c = Math.round(2.5);
Output
b is now 3
c is now 3
But
var c = Math.round(-2.7);
var c = Math.round(-2.5);
Output
c is now -2
Rounding up
Math.ceil() will round the value up.
var a = Math.ceil(2.3);
var b = Math.ceil(2.7);
Output
b is now 3
ceiling a negative number will round towards zero
var c = Math.ceil(-1.1);
Output
Rounding down
Math.floor() will round the value down.
var a = Math.ceil(2.3);
var b = Math.ceil(2.7);
Output
b is now 3
ceiling a negative number will round towards zero
var c = Math.ceil(-1.1);