Let's start with a normal split:
var result = 3/2;
As noted, this operation has resulted in 1.5
, which is not what we want.
To have a whole split, we have to decide what kind of rounding we intend to use.
The main options are:
- Round down ( by default ). This is the rounding form that Ruby uses .
- Round to the nearest number.
- Round up ( by excess ).
- Truncate the result (round down to positive numbers, up to negative numbers). This form of rounding is very common in the whole division of other programming languages, such as C.
Example:
var arredondadoParaBaixo = Math.floor(3/2);
var arredondadoParaProximo = Math.round(3/2);
var arredondadoParaCima = Math.ceil(3/2);
To truncate the result, we have more than one way. The Math.trunc
function was introduced in ECMAScript 6 but this function is quite recent so it is not universally supported by Internet browsers.
An alternative way to truncate is to "force" the number to be integer. One of the simplest ways to do this is to use bit-by-bit operations, but do nothing.
var truncado = (3/2)|0;
This does the OR bit-by-bit operation with the number 0.
The "OR" converts the number to integer before performing the operation, but otherwise, OR with 0 is as sum with 0 or multiplication with 1 - does nothing.
Other forms used include ~~(3/2)
, (3/2)^0
, (3/2)<<0
and (3/2)>>0
.
The (3/2)&0
does not serve because the operation E with 0 always has 0 result, which is not what we want.
If the result does not fit a signed 32-bit integer (complement of two), the division with zeroing ignores the remaining bits, so the result may be different than expected in these cases (jsfiddle ).
If we are facing a division by zero, the methods floor
, round
, ceil
, and trunc
do not change the result (thus returning infinite or NaN
), whereas the |0
results 0
( jsfiddle ).