Python:将小数转换为月份

标签 python date decimal

下面的函数返回:您的 6.25 年月供为 529.22 美元,首付为 4620.06 美元。

如何将小数转换为 4 个月而不是 0.25 年。

我希望输出为:您的 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())

最佳答案

您可以将年份转换为整数,并将小数部分 * 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

在调用该函数之前,您可以检查持续时间是否至少为一个月。

关于Python:将小数转换为月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43351185/

相关文章:

python - Decimal 类可以处理的最大数字是多少?

python - Matplotlib 设置,用于保存用于发布的图形和来自交互式绘图的报告

python - 消除python脚本中最后一个字符串后的文本

PHP 日期问题,无法转换 1970-01-01 之前的日期

php - 将包含月数的变量转换为 X 年,X.5 个月格式?

Java- 小数点后 2 位四舍五入 *不仅仅是 %.2f*

python - ElementTree元素索引查找

python - HSV 到 RGB 颜色转换

PHP 比较两个日期和时间

.NET:将日期时间转换为十进制