Ian Ian - 7 months ago 27
Javascript Question

Easiest way to convert a number into years and months

I have a script that generates a number and sets it to a textbox. If, for example, the number was 6.3, I'd want to be able to convert this into 6 years 4 months.

Is there a quick way to do this?

var n = 6.3;
var y = Math.floor(n);            // whole years
var m = Math.floor(12 * (n - y)); // treat remainder as fraction of a year

I note that this gives 3 for the month, not 4. Why do you think 6.3 should give 4 months? 6 years and 4 months is 6.333333 years.