round(value,2)有什么作用?

时间:2015-05-12 21:30:39

标签: python rounding

我目前正在通过麻省理工学院开放式课程参加免费在线课程。我遇到了一个问题,我正在努力理解解决方案。我不确定" 2"是在做。它是(minMonthlyPaymentRate *余额中的两个,2)这是解决方案:

# 6.00 PS1-A Solution
# Determines remaining credit card balance after a year of making the minimum payment each month

balance = float(raw_input("Enter the outstanding balance on your credit card: "))
annualInterestRate = float(raw_input("Enter the annual credit card interest rate as a decimal: "))
minMonthlyPaymentRate = float(raw_input("Enter the minimum monthly payment rate as a decimal: "))

# Monthly Interest Rate
monthlyInterestRate = annualInterestRate/12

# Initialize state variables
numMonths = 1
totalAmtPaid = 0

while numMonths <= 12:
    # Minimum monthly payment of balance at start of the month
    minPayment = round(minMonthlyPaymentRate * balance,2)**This Two!?**
    totalAmtPaid += minPayment

    # Amt of monthly payment that goes to interest
    interestPaid = round(monthlyInterestRate * balance,2)

    # Amt of principal paid off
    principalPaid = minPayment - interestPaid

    # Subtract monthly payment from outstanding balance
    balance -= principalPaid

    print "Month:", numMonths
    print "Minimum monthly payment:", minPayment
    print "Remaining balance:", balance

    # Count this as a new month     
    numMonths += 1

print "RESULT"
print "Total amount paid:",totalAmtPaid
print "Remaining balance:",balance

3 个答案:

答案 0 :(得分:0)

python documentation of the function round()中所示,它表示&#34;四舍五入到小数点后的数字位数&#34;。所以这意味着结果将四舍五入到小数点后的两位数。

答案 1 :(得分:0)

一张图片胜过千言万语。

enter image description here

答案 2 :(得分:0)

ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(json); String sender = jsonNode.get(0).get("sender").textValue(); 会四舍五入为给定的位数并返回浮点数。

示例代码:

round()