我试图在Python中将输出格式化为两个小数位..这是我的代码def introduction():
print("This calculator calculates either the Simple or Compound interest of an given amount")
print("Please enter the values for principal, annual percentage, number of years, and number of times compounded per year")
print("With this information, we can provide the Simple or Compound interest as well as your future amount")
def validateInput(principal, annualPercntageRate, numberOfYears,userCompound):
if principal < 100.00:
valid = False
elif annualPercntageRate < 0.001 or annualPercntageRate > .15:
valid = False
elif numberOfYears < 1:
valid = False
elif userCompound != 1 and userCompound != 2 and userCompound != 4 and userCompound != 6 and userCompound != 12:
valid = False
else:
valid = True
return valid
def simpleInterest(principal, annualPercentageRate, numberOfYears):
return (principal * annualPercentageRate * numberOfYears)
def compoundInterest(principal, annualPercentageRate, numberOfYears, userCompound):
return principal * ((1 + (annualPercentageRate / userCompound))**(numberOfYears * userCompound) - 1)
def outputAmounts(principal, annualPercentageRate, numberOfYears, userCompound, simpleAmount,compoundAmount):
print("Simple interest earned in", numberOfYears, "will be $",simpleAmount,"making your future amount $",(principal + simpleAmount)
print("Interest compounded", userCompound, "in",numberOfYears, "will earn $",compoundAmount,"making your future amount",(principal + compoundAmount)
def main():
introduction()
principal = float(input("Enter principal: "))
annualPercentageRate = float(input("Enter rate: "))
numberOfYears = int(input("Enter years: "))
userCompound = int(input("Enter compounding periods: "))
if validateInput(principal, annualPercentageRate, numberOfYears, userCompound):
simpleAmount = simpleInterest(principal, annualPercentageRate, numberOfYears)
compoundAmount = compoundInterest(principal, annualPercentageRate, numberOfYears, userCompound)
outputAmounts(principal, annualPercentageRate, numberOfYears, userCompound, simpleAmount,compoundAmount)
else:
print("Error with input, try again")
main()
所以对于我的输出,我想将结尾格式化为两个小数位。也就是说,这两个变量
-(委托人+合作方)
-(委托人+simpleAmount)
我知道我需要使用.2,但我不确定如何将它添加到print语句中,以便它输出到小数点后两位…我该如何做?