Andrew Lastrapes
Andrew Lastrapes

Reputation: 187

Python: Converting decimals into months

The function below returns: Your monthly payment would be $529.22 for 6.25 years, and a downpayment of $4620.06.

How could I convert the decimal to 4 months instead of .25 years.

I would like the output to read: Your monthly payment would be $529.22 for 6 years and 4 months, and a downpayment of $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())

Upvotes: 2

Views: 1095

Answers (1)

Eric Duminil
Eric Duminil

Reputation: 54313

You could convert the years to an integer and convert the decimal part * 12 to a month :

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))

It outputs:

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

Before calling this fonction, you could check that the duration is at least a month.

Upvotes: 3

Related Questions