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


Converting a variable containing the number of months to X Years, X.5 Months format?

我使用了以下代码来实现这一点:

$total_months = 59;
$years  = (int)($total_months / 12);
$months = $total_months % 12;

输出4年11个月…

如果输入是:

$total_months = 59.5; 
$years  = (int)($total_months / 12);
$months = $total_months % 12;

我需要4年零11.5个月的产出…

有人能帮我看看结果吗?

你可以这样做:

$months = fmod($total_months, 12);
$total_months = 59.5; 
$sub_month=$total_months - floor($total_months);
$years  = (int)($total_months / 12);
$months = $total_months % 12;
$months=$months+$sub_month;