How do I make a whole division?

26

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

3/2
=> 1

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

3.0/2
=> 1.5

How can I make a whole division that works similar to ruby in javascript?

    
asked by anonymous 18.02.2014 / 00:00

3 answers

27

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 ).

    
18.02.2014 / 00:09
7

More explicit is with the function Math.floor (round down):

Math.floor(3/2)
> 1

Alternatively, use parseInt

parseInt(3/2) //ou parseInt(3/2, 10);
> 1
    
18.02.2014 / 00:07
2

JavaScript automatically divides a decimal result, but you can convert the decimal result to Inteiro so that you have the result you want.

Examples:

With decimal ( default ):

3/2;
=> 1.5

Integer ( with conversion )

parseInt(3/2);
=> 1
    
18.02.2014 / 00:04