Ian
Ian

Reputation: 865

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?

Upvotes: 1

Views: 5047

Answers (5)

Carlos Ost
Carlos Ost

Reputation: 512

var n = 6.3
var years = Math.floor(n);
var months = Math.round((n * 12) % 12);

% means modulus and it returns the remainder of the division, while round, rounds a number to its nearest integer.

So...

  • Math.floor(6.3) will return 6 years
  • (6.3 * 12) % 12 will return 3.6 months
  • round(3.6) will return 4 months and this explains why 6.3 years is like 6 years and 4 months.

Upvotes: 0

Manse
Manse

Reputation: 38147

Im really not sure if you want to create a date/number from your input or just split the numbers and make a string ? i went for the second one !

var number = 6.3;
var splitstring = number.toString().split('.');
var years = splitstring[0];
var months = splitstring[1];
alert(years + ' years,' + months + ' months');​

Working example here

Upvotes: 1

Alnitak
Alnitak

Reputation: 340045

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.

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123428

var num = 8.62;
console.log("%d year/s and %d month/s", ~~num, ~~((num - ~~num)*12)); 
/* 8 year/s and 7 month/s */

Upvotes: 0

Roland Mai
Roland Mai

Reputation: 31097

function getDescription(str)
{
    var description = "";
    var years = 0;
    var months = 0;
    var splits = str.split('.');
    if(splits.length >= 1)
    {
       years = parseInt(splits[0]);
    }
    if(splits.length >= 2)
    {
       months = parseInt(splits[1]);
    }
    return years + ' years' + ' ' + months + ' months';
}

call with

getDescription('6.3');

or

getDescription(document.getElementById('my_textbox').value);

Upvotes: 0

Related Questions