Forum Moderators: coopster

Message Too Old, No Replies

Months to Years and Months function

Seems easy, but can't get it right.

         

neophyte

3:51 am on Mar 27, 2007 (gmt 0)

10+ Year Member



Hello All -

I've got the need for a function which takes any number of months and converts that number into years and remaining months.

I thought, "oh, easy" and did this:

<?php
function monthsToYears($months)
{

$a = $months / 12;
$b = round($a,1);

return $b;
}
?>

<?php
echo monthsToYears(16);
?>

returned value would be x(years).y(remaining months, if any)

Works great until you feed the function a 16, which then returns "1.3" instead of what I expected: 1.4.

I've tried to just divide the months by 12 and then do a fmod for the remainder, but that isn't working either for certain numbers.

I'm sure this has been done before for various reasons, so could someone please shed some light on what I need to do to get the correct return values for any number of months input?

Great appreciation in advance.

Neophyte

willybfriendly

4:02 am on Mar 27, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You need to use the modulus operator [us3.php.net]

<?
//function to convert months to years and months
function mos2yrs($months)
{
$years = intval($months/12);
$months = $months%12;

return "$years yrs and $months mos";
}
?>

That should work.

WBF

neophyte

5:22 am on Mar 27, 2007 (gmt 0)

10+ Year Member



willybfriendly -

Thank you VERY much. Works like a charm. Will give the modulus operator for future reference.

Thanks again!

Neophyte