2017-04-11 3 views
2

아래 함수가 반환됩니다. 월 지불액은 6.25 년에 $ 529.22, $ 4620.06의 선금이됩니다.Python : 월 단위로 소수 자릿수 변환

어떻게 십진수를 0.25 년 대신 4 개월로 변환 할 수 있습니까?

출력을 읽기를 원합니다. 월 지불액은 6 년 4 개월 동안 $ 529.22, $ 4620.06의 하향 지불입니다.

def newcar(): 

input("How much is a new car going to cost you per month? Please hit 
enter to start") 
p = int(input("Please enter total cost of car: ")) 
r = float(input("Please enter interest rate as a whole number(example: 
15.6% = 15.6): National average is around 10.5%): ")) 
t = int(input("These payments would last for how many months?: ")) 
dp = int(input("Please enter the downpayment percentage as a whole 
number: example: 20% = 20: ")) 
afterdp = p - (p * dp/100) 
downpay = p - afterdp 
downpay = round(downpay, 2) 
interest = afterdp * (r/100) * (t/12) 
interest = round(interest, 2) 
monthly_payment_bt = (afterdp + interest)/t 
monthly_payment_bt = round(monthly_payment_bt, 2) 
monthly_payment = (monthly_payment_bt * .07) + monthly_payment_bt 
monthly_payment = round(monthly_payment, 2) 
t = round(t/12, 2) 
return("Your monthly payment would be $" + str(monthly_payment) + " 
for " + str(t) + " years, and a downpayment of $" + str(downpay)) 

print(newcar()) 
+4

단지'.25 * 12' 그리고'round()'it ... Btw, 1 년 중 25 %는 3 개월이 아니라 4 개월이됩니다. –

+1

나는 관심을 계산하지 않을 것이라고 확신합니다. 바르게. 일반적으로이자는 매월 혼합되므로 이미 지불 한 부분에이자를 내지 않습니다 (그러나 이전이자에 대한이자 지급). [이 수식] (https://en.wikipedia.org/wiki/Mortgage_calculator#Monthly_payment_formula)을 사용하고 분수가 아닌 정수 값으로 계산을하는 것이 좋습니다. – Blckknght

답변

3

당신은 한 달에 * (12)를 정수로 년 변환과 소수 부분을 변환 할 수 있습니다 :

def singular_or_plural(count, word): 
    if count == 1: 
     return "1 %s" % word 
    elif count > 1: 
     return "%d %ss" % (count, word) 


def years_and_months(float_year): 
    year = int(float_year) 
    month = int((float_year % 1) * 12) 
    words = [(year, 'year'), (month, 'month')] 
    return ' and '.join(singular_or_plural(count, word) 
         for (count, word) in words if count > 0) 

print(years_and_months(0.09)) 
print(years_and_months(0.50)) 
print(years_and_months(1)) 
print(years_and_months(2)) 
print(years_and_months(2.5)) 
print(years_and_months(2.99)) 
print(years_and_months(6.25)) 

그것은 출력 :

1 month 
6 months 
1 year 
2 years 
2 years and 6 months 
2 years and 11 months 
6 years and 3 months 

, 당신은 할 수이 fonction를 호출하기 전에 기간이 적어도 한 달인지 확인하십시오.