我正在制作EMI计算器,该计算器会在显示每月EMI之后显示摊销表。
如何将货币符号与任何n位十进制数字右对齐?
我尝试使用'{0}{1:5.2f}'.format(rupee, amount)
来使货币符号和金额正确对齐,但是并不能解决指出格式字符串不正确的问题。
金额是浮点数,小数点后2位以上,需要四舍五入到小数点后2位。
以下是显示4个金额值的代码(我使用INR作为货币符号):
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))
需要在此示例代码中进行一些编辑以使货币符号和金额正确对齐,但我无法弄清楚。
实际输出:
$1.07
$22.34
$213.08
$4.98
预期输出:
$1.07
$22.34
$213.08
$4.98
将$
符号用作货币符号,因为不能直接从键盘上输入卢比符号。
答案 0 :(得分:2)
稍微扩展上一个答案:
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)))
输出:
₹12345.67
₹1.07
₹22.34
₹213.08
₹4.98
答案 1 :(得分:1)
如果您知道输出中的最大字符数,则可以执行以下操作。有关各种可用格式说明符,请参见Format Specification Mini-Language。
amounts = ['$1.07', '$22.34', '$213.08', '$4.98']
for amount in amounts:
print('{:>8}'.format(amount))
# OUTPUT
# $1.07
# $22.34
# $213.08
# $4.98