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?
– Thiago Henrique
This @Thiagohenrique
– Eduardo Roberto Ferreira
Try to round the sum result: Math.round(summePercentual.push(percentage))
– Antonio C. da Silva Júnior
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 ifnum
for 4 gives you[25, 25, 25, 25]
– Isac
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()
– Eduardo Roberto Ferreira