Odd number calculation - JavaScript

0

I'm trying to divide 100 by a number so I get the percentage of that number to play in a variable that is within a FOR ... and that FOR throws the percentage in of an Array ... More or Less Thus:

var numero = 4

var percentual = 100/numero

var somaPercentual = new Array();

for(i=0;i<numero;i++){

    var porcentagem = percentual

    somaPercentual.push(porcentagem)

}

In this case my Array would come:

25,25,25,25

So I need to add the Array values and give 100! So far so good ... the headache starts when the number that will be divided by 100 is an Odd number!

If the variable number is equal to 3 for example, my Array would give = 33.33, 33.33, 33.33, where the sum would give 99.99 .... and then mess it up! This always happens when the number is odd.

Can someone give me a light?

[EDIT] I solved using .Reduce ():

document.querySelector('button').addEventListener('click', () => {
  var number = document.querySelector('input').value;
  var percentage = 100 / number
  var somaPercentual = new Array();
  for (i = 0; i < number; i++) {
    i < number - 1 ?
      somaPercentual.push(percentage) :
      somaPercentual.push(100 - somaPercentual.reduce((a, b) => {
        return a + b
      }));
  }

  console.log(somaPercentual)
  console.log(somaPercentual.reduce((a, b) => {
    return a + b
  }))
})
<input type="number" value="3" />
<button>calc</button>
    
asked by anonymous 14.06.2018 / 14:52

3 answers

0

In this case you can use Math.ceil to round up, as there are always a few fractions missing solves your problem.

I used from this answer to resolve the decimal rounding / cropping problem.

var numero = 7

var percentual = 100/numero

var somaPercentual = new Array();

for(i=0;i<numero;i++){
    var porcentagem = Math.floor(percentual * 100) / 100; 
    somaPercentual.push(porcentagem)
};

var soma = 0;

for(i=0;i<somaPercentual.length;i++){
    console.log(somaPercentual[i]);
    soma += somaPercentual[i];
}

soma = Math.ceil(soma); //Math.ceil retorna o maior inteiro mais próximo (2.4 = 3)

console.log(soma);
    
14.06.2018 / 15:07
0

Dude, if you split 100 to 3, you'll get 33.33, rounding down, giving 33% for each. It's impossible to always give 100, it does not make sense.

To round down you can use Math.floor()

let a = 100/3
    let b = 100 % 3;
    console.log(Math.floor(a) + '% o resultado e sobram ' + b + '%');

What you can do is exactly that, pick up the rest and add some index if your array:

var numero = 3

var percentual = 100/numero

var somaPercentual = new Array();

for(i=0;i<numero;i++){

    var porcentagem = percentual

    somaPercentual.push(Math.floor(porcentagem));

}

let somarVal = somaPercentual[somaPercentual.length - 1] + (100 % numero);

somaPercentual.push(somarVal);

console.log(somaPercentual);
    
14.06.2018 / 16:12
0

Expanding slightly on the solution you put in

15.06.2018 / 01:03