Search code examples
pythonpython-3.xstring-formatting

How to print currency symbol and an n-digit decimal number right aligned in Python


I'm making an EMI calculator, which displays an amortization table after displaying monthly EMI.

How can I right align the currency symbol and any n-digit decimal number?

I tried to right align currency symbol and amount by using '{0}{1:5.2f}'.format(rupee, amount) but it didn't solve the problem stating incorrect format string.

The amounts are floating point numbers with more than 2 decimal places, they need to rounded off upto 2 decimal places.

Here's the code which displays 4 amount values (I'm using INR as the currency symbol) :

rupee = chr(8377)
print('{0}{1:.2f}'.format(rupee, amount1))
print('{0}{1:.2f}'.format(rupee, amount2))
print('{0}{1:.2f}'.format(rupee, amount3))
print('{0}{1:.2f}'.format(rupee, amount4))

Some edits need to be made in this sample code to right align the currency symbol and amount, but I'm not able to figure that out.

Actual Output:

$1.07
$22.34
$213.08
$4.98

Expected Output:

  $1.07
 $22.34
$213.08
  $4.98

Taking $ symbol as the currency symbol because the rupee symbol can't be typed directly from the keyboard.


Solution

  • Extending the previous answer a little:

    rupee = u'\u20B9'
    amounts = [12345.67, 1.07, 22.34, 213.08, 4.98]
    
    for amount in amounts:
        print('{:>10}'.format(rupee + '{:>.2f}'.format(amount)))
    

    Output:

     ₹12345.67
         ₹1.07
        ₹22.34
       ₹213.08
         ₹4.98