Odd Number Calculation - Javascript

Asked

Viewed 396 times

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 plays the percentage within of an Array... More or Less So:

var numero = 4

var percentual = 100/numero

var somaPercentual = new Array();

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

    var porcentagem = percentual

    somaPercentual.push(porcentagem)

}

In that case my Array would come :

25,25,25,25

Then I need to add the values of the Array and give 100! So far so good... the headache begins 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 = 33.33, 33.33, 33.33, where the sum would be 99.99.... and then mess everything up! This always happens when the number is odd.

Someone can give me a light?

[EDIT] I solved using the . 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>
  • You need exactly what? Of integer values?

  • This @Thiagohenrique

  • Try to round the sum result: Math.round(summePercentual.push(percentage))

  • But what exactly are you trying to do? See the parcels that 100 divided by another number gives ? If it were 100 by 3, what would be the plots you want to get ? It is that for this objective nor need one, just new Array(num).fill(100/num) in which if num for 4 gives you [25, 25, 25, 25]

  • To better understand the purpose... I am sending data to a system, and this system only accepts the "percentage" field if the sum of all the "percentage" fields is 100 ! I was able to solve using . Reduce()

3 answers

0

Expanding a little bit on the solution you put as EDIT, to divide 100 in several equal instalments does not need to for. In any case, there are several cases where it will not be possible to have equal portions, because 100 will not be divisible by multiple numbers.

The simplest logic is to divide by the number you want to get the value of each installment, then sum all but one, the last, which gets the missing value to do 100.

An example of this logic applied to your code:

document.querySelector('button').addEventListener('click', () => {
  let number = document.querySelector('input').value;
 
  let parcelas = new Array(number - 1).fill(100 / number);
  let total = parcelas.reduce((acc, curr) => curr + acc, 0);
  parcelas.push(100 - total);
  console.log(parcelas);
});
<input type="number" value="3" />
<button>calc</button>

The new Array(number - 1) creates an array with number - 1 elements, and the fill fills these elements with the past value. Then the total is found with reduce.

0

In that case you can use the Math.Ceil to round up, as will always miss a few fractions this solves your problem.

I used of that answer to solve the problem of decimal rounding/cutting.

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

  • To numero = 7, the result will be 101.

  • @Andersoncarloswoss validates for me if it’s right?

  • @A.Junior the sum should always return 100. For there may be some case where the sum = 99.4 if using Round will return 99 and not 100.

  • You are right. I still don’t understand the purpose of this, but suddenly in the solution using Math.Ceil, put a conditional to "crash" in 100 case you pass 100.

  • To better understand the purpose... I am sending data to a system, and this system only accepts the "percentage" field if the sum of all the "percentage" fields is 100 ! I was able to solve using . Reduce()

0

Dude, if dividing 100 to 3 is going to be 33.33, rounding it down, it would be 33% each. It’s impossible to always give 100, it doesn’t make sense.

To round down you can use the 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 just that, pick up the rest and add in some dice 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);

  • I edited to get better and more complete the answer, with a possible alternative for you to solve your problem.

  • To better understand the purpose... I am sending data to a system, and this system only accepts the "percentage" field if the sum of all the "percentage" fields is 100 ! I was able to solve using . Reduce()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.