Let’s start with a normal division:
var result = 3/2;
As noted, this operation has resulted 1.5
, that’s not what we want.
To have an entire division, we have to decide what kind of rounding we want to use.
The main options are:
- Round down (default). Is this the rounding shape that Ruby uses.
- Round to nearest number.
- Round up (overpowering).
- Truncate the result (round down to positive numbers, up to negative numbers). This form of rounding is very common in the entire 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 function Math.trunc
was introduced in Ecmascript 6 (recent Javascript standard), 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 whole. One of the simplest ways to do this is to use bit-to-bit operations, but do nothing.
var truncado = (3/2)|0;
This makes the bit-by-bit operation with the number 0.
"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 the ~~(3/2)
, the (3/2)^0
, the (3/2)<<0
and the (3/2)>>0
.
The (3/2)&0
does not serve because the operation E with 0 has always result 0, which is not what we want.
If the result does not fit into a 32-bit integer with signal (complement of two), the division with truncature ignores the remaining bits, so the result may be different than expected in these cases (jsfiddle).
If we are faced with a division by zero, the methods floor
, round
, ceil
and trunc
do not change the result (thus returning infinite or NaN
), while the truncation using the |0
results 0
(jsfiddle).
In my opinion Math.Trunc is preferable. To maintain compatibility with previous versions, I would make a function to use in my application:
roundDivision = Math.Trunc || BitwiseOr;
Whose function argumentBitwiseOr
also the number and the result would beArg | 0;
– EProgrammerNotFound