Python: Rounding to Nearest 1/8%
<p>I'm trying to calculate the average weighted interest rates of loans in Python 2.7. </p>

<p>I started out with floats, and that was problematic. Given these inputs (Loan #1 $20,000 6.80%; Loan #2 $10,000 7.90%; Loan #3 $10,000 5.41%) the correct result is 6.7275. Using Decimal, my code outputs that. </p>

<p>However, I am supposed to take that number and round <del>up</del> to the nearest 1/8% and display the result as 6.75 instead. When I use format to round to two places, I get 6.73. While that is what I would expect, is does not meet the scope of what this function should do.</p>

<pre><code>from decimal import Decimal

def weightedAvgFixedArgs(r1,r2,r3,b1,b2,b3):
    rates = [Decimal(r1),Decimal(r2),Decimal(r3)]
    balances = [Decimal(b1),Decimal(b2),Decimal(b3)]

    a = Decimal(b1) * Decimal(r1)
    b = Decimal(b2) * Decimal(r2)
    c = Decimal(b3) * Decimal(r3)

    perLoanWghtFctr = a + b + c

    totalLoanAmt = sum(balances)

    intRate = (perLoanWghtFctr / totalLoanAmt) * 100

    return format(intRate, '.2f')
</code></pre>

<p>Edit: Joachim Isaksson's suggestion provides the output I requested with the inputs I provided. I haven't tested this extensively in my particular use-case, but it correctly answers the question I asked.</p>

<pre><code># return format(intRate, '.2f')
z = intRate * 8
y = format(z, '.0f')
x = Decimal(y) / Decimal(8)
return x
</code></pre>