Jasir alwafaa - 1 year ago 76
jQuery Question

# jQuery find percentage array based on selected value

I have a select box having number count like;

``````<select>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
``````

If I select one option it will take as number of customer. Then I ant to calculate percentage out of 100 for each customer in jQuery and save in a jQuery array.

If I select 2 then create an array
`var perc= ["50", "50"];`

If selected value is 3, array become
`var perc = ["33", "33", "34"];`

How can I do that, I tried like

``````var arr1 = [];
for(var k=0;k<num_cust;k++){
var perc_vl = parseFloat(100) / parseFloat(num_cust);
arr1[] = perc_vl;
}
``````

But it will only divide equally...

You can use `Math.ceil` and `Math.floor` to do this like following.

``````\$('select').change(function() {
var num_cust = this.value,
arr1 = [];

for (var k = 0; k < num_cust; k++) {
var perc_vl = 100 / num_cust;

if (k == num_cust-1) {
perc_vl = Math.ceil(perc_vl);
} else {
perc_vl = Math.floor(perc_vl);
}

arr1.push(perc_vl);
}

``````<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>