2012-04-17 183 views
1

我有一个脚本,用于生成一个数字并将其设置为文本框。例如,如果数字是6.3,我希望能够将其转换为6年4个月。将数字转换为年和月的最简单方法

有没有快速的方法来做到这一点?

+0

您预期的产量是多少?一个字符串? 2号码?以及6.3 = 6年和** 4 **月是怎样的? – ManseUK 2012-04-17 09:09:04

回答

1
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 

我注意到这给出了3个月,而不是4.你为什么认为6.3应该给4个月? 6年4个月是6.333333年。

1

我真的不确定你是否想从你的输入中创建一个日期/数字,或者只是分割数字并创建一个字符串?我去了第二个!

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

0
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'; 
} 

呼叫与

getDescription('6.3'); 

getDescription(document.getElementById('my_textbox').value); 
0
var num = 8.62; 
console.log("%d year/s and %d month/s", ~~num, ~~((num - ~~num)*12)); 
/* 8 year/s and 7 month/s */ 
0
var n = 6.3 
var years = Math.floor(n); 
var months = Math.round((n * 12) % 12); 

%意思是模数,它返回除法的其余部分,while round将数字舍入到最接近的整数。

所以......

  • Math.floor(6.3)将返回6年
  • (6.3 * 12)%12将返回3.6个月
  • 轮(3.6)将返回4个月这解释了为什么6.3 年如6年4个月
相关问题