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>