percentage calculation formatting

mail@pastecode.io avatar
unknown
python
2 years ago
1.4 kB
2
Indexable
Never
#roundGrid.py
#function to round an arbitrary number of rows to predefined total
import math
total=7
rows = [1,1,1,1,1,1,1]

#pass in the array of values as rows, the totalItems is the expected sum of rows values, totalPercent is usually 100
def getPercentageList(rows,totalItems,totalPercent):
    precision = 1
    percentageList = []
    calcTotal = 0
    for x in rows:
        #convert the calculated percent to a percentage in appropriate viewing format
        calc = (x/total)*totalPercent
        num = round(calc,1)
        percentageList.append(num)
        calcTotal = calcTotal+num
    
    print("real percentages: ",percentageList)

    difference = round(totalPercent-calcTotal,precision)
    if difference != 0:
        step = 1 / (precision*10)
        print("difference is %f, step is %f" % (difference,step))
        if difference > step:
            difference = math.ceil(difference)
        #now spread the difference by step until the difference is covered
        for i in range(len(percentageList)):
            if difference > 0:
                percentageList[i] = round(percentageList[i]+step,precision)
                difference = difference - step
            if difference < 0:
                percentageList[i] = round(percentageList[i]-step,precision)
                difference = difference + step
    
    return percentageList

print("adjusted percentages: ",getPercentageList(rows,total,100))