javascript – How do I make an entire division?


Using ruby, the division of two integers is an integer division, that is, the result is an integer. For example:

=> 1

If I want the result to be a decimal number, I can use a floating number instead of an integer:

=> 1.5

How can I make an integer division that works similar to ruby ​​in javascript?


Let's start with a normal division:

var result = 3/2;

As noted, this operation has a result of 1.5 , which is not what we want.

To have an integer division, we have to decide what kind of rounding we want to use.

The main options are:

  • Round down ( default ). This is the form of rounding that Ruby uses .
  • Round to the nearest number.
  • Round up ( by excess ).
  • Truncate the result (round down for positive numbers, up for negative numbers). This form of rounding is very common in integer division in other programming languages ​​such as C.


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 (a recent JavaScript standard), but this function is quite new and is not universally supported by Internet browsers.

An alternative way to truncate is to "force" the number to be an 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 bit-by-bit OR operation with the number 0.

The "OR" converts the number to an integer before performing the operation, but otherwise, OR with 0 is like adding to 0 or multiplying to 1 — it does nothing.

Other forms used include ~~(3/2) , (3/2)^0 , (3/2)<<0 and (3/2)>>0 .

The (3/2)&0 doesn't work because the AND operation with 0 always results in 0, which is not what we want.

If the result does not fit into a 32-bit signed integer (two's complement), the truncation division 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 floor , round , ceil and trunc methods do not change the result (thus returning infinity or NaN ), while truncation using |0 gives the result 0 ( jsfiddle ).

Scroll to Top