如何在Python中将输出格式化为2个小数位?

Moh*_*ind -2 python decimal

我正在尝试将输出格式设置为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()
Run Code Online (Sandbox Code Playgroud)

因此,对于我的输出,我想将结尾格式设置为2个小数位。即,这两个变量-(principal + compoundAmount)-(principal + simpleAmount)

我知道我需要使用%.2,但是我不确定如何将其添加到打印语句中,以便将其输出到2个小数位...我该怎么做?

小智 5

尝试这个

print('pi is {:.2f}'.format(your_variable))
Run Code Online (Sandbox Code Playgroud)