Reputation: 865
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
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...
Upvotes: 0
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');
Upvotes: 1
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
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
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