[英]What changes should I do for the output to display with two decimal places?
I want my output to have a 2 decimal places result.我希望我的 output 结果有 2 位小数。 What should I do?我应该怎么办? Ideal output is:理想的 output 是:
Enter the number of plants to purchase: 14输入要购买的植物数量:14
Enter the price per unit of plant: 250.00输入每株植物的价格:250.00
The total payable amount is: P3,350.00应付总额为:P3,350.00
n1 = input('Enter number of plants: ')
n2= input('Enter price per unit: ')
mul= float(n1) * float(n2)
mul2= (float(n1)-float(10)) * (float(n2))
mul3 = float(10) * float(n2)
discount2 = float (mul2)* float(0.15)
total2=mul2-discount2
total3= total2+mul3
if float(n1)<=float(10):
mul= float(n1) * float(n2)
print('The total payable amount is: ', mul)
elif float(n1)>float(10):
print('The total payable amount is: ', total3)
You can use the str.format
function and I made some small adjustments to your code.你可以使用str.format
function 我对你的代码做了一些小的调整。
n1 = float(input('Enter number of plants: '))
n2= float(input('Enter price per unit: '))
mul = n1 * n2
if n1<=10:
print('The total payable amount is: {:.02f}'.format(mul))
else:
print('The total payable amount is: {:.02f}'.format(0.85*mul+1.5*n2))
A few answers missed the fact you also needed thousands separated by a comma.一些答案错过了您还需要用逗号分隔数千个的事实。 here is the format
command which displays the price the way you expect it这是format
命令,它以您期望的方式显示价格
n1 = input('Enter number of plants: ')
n2= input('Enter price per unit: ')
mul= float(n1) * float(n2)
mul2= (float(n1)-float(10)) * (float(n2))
mul3 = float(10) * float(n2)
discount2 = float (mul2)* float(0.15)
total2=mul2-discount2
total3= total2+mul3
if float(n1)<=float(10):
mul= float(n1) * float(n2)
print('The total payable amount is: ${:0,.2f}'.format(mul))
elif float(n1)>float(10):
print('The total payable amount is: ${:0,.2f}'.format(total3))
Use a formatted string .使用格式化的字符串。 Also, convert the values to floats at the start, then there is no need to keep converting everything.此外,在开始时将值转换为浮点数,然后无需继续转换所有内容。
plants_str = input('Enter number of plants: ')
price_str = input('Enter price per unit: ')
plants = float(plants_str)
price = float(price_str)
total = plants * price
if plants > 10:
total -= 0.15 * (plants - 10) * price
print(f"The total payable amount is: {total:0,.2f}")
But as noted in a comment, for serious applications involving currency you should use the decimal library.但正如评论中所指出的,对于涉及货币的严肃应用程序,您应该使用十进制库。 This ensures decimal numbers are represented exactly.这确保了十进制数字的精确表示。
from decimal import Decimal
plants_str = input('Enter number of plants: ')
price_str = input('Enter price per unit: ')
plants = Decimal(plants_str)
price = Decimal(price_str)
total = plants * price
if plants > 10:
total -= Decimal("0.15") * (plants - 10) * price
print(f"The total payable amount is: {total:0,.2f}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.