我们有一个年/月 HTML 控件。基础价值保留为小数。例如:15 年零 2 个月等于“15.02”。
我们希望根据 2 年/月控制(加/减)进行计算。
只做基本的数学计算是行不通的:
Value1 : 65.00
Value2 : 47.09
65.00 - 14.09 = 17.91
(is wrong, but should be 17.03 or (64.12 - 47.09))
是否有任何 Javscript/Jquery 函数或我可以用来进行年/月计算的库?
我们有一个年/月 HTML 控件。基础价值保留为小数。例如:15 年零 2 个月等于“15.02”。
我们希望根据 2 年/月控制(加/减)进行计算。
只做基本的数学计算是行不通的:
Value1 : 65.00
Value2 : 47.09
65.00 - 14.09 = 17.91
(is wrong, but should be 17.03 or (64.12 - 47.09))
是否有任何 Javscript/Jquery 函数或我可以用来进行年/月计算的库?
只需将月份部分转换为常规小数(除以 12),进行数学运算,然后将小数部分转换回月份(乘以 12)。
您必须使用类似var bits = Value1.split(".");. 年份是bits[0]和月份bits[1]。
例如47.09将是47 + (9 / 12 = 0.75) = 47.75。
所以65 - 47.75 = 12.25。
将小数部分转换回月份:0.25 * 12 = 0.3. 所以答案是47.03。
JavaScript 不支持运算符重载,因此我认为您无法找到一种解决方案,让您可以逐字地使用+复合-年/月值。
但是,您可以使用加法和减法定义自己的年/月对象类型:
function YearsMonths(years, months) {
this.years = years;
if (months > 11) {
this.years = this.years += Math.floor(months/12);
this.months = months % 12;
}
else {
if (months < 0) {
this.months = 12 + (months % -12);
this.years -= (Math.floor(months/-12) + 1);
}
else {
this.months = months;
}
}
}
YearsMonths.prototype.add = function (otherYearsMonths) {
newYears = this.years + otherYearsMonths.years;
newMonths = this.months + otherYearsMonths.months;
return new YearsMonths(newYears, newMonths);
}
YearsMonths.prototype.subtract = function (otherYearsMonths) {
var newYears = this.years - otherYearsMonths.years,
newMonths = this.months - otherYearsMonths.months;
return new YearsMonths(newYears, newMonths);
}
然后像这样使用它:
value1 = new YearsMonths(65, 0);
value2 = new YearsMonths(47, 9);
value3 = value1.subtract(value2);
value4 = value1.add(value2);
value3.years;
# 17
value3.months;
# 3
value4.years;
# 112
value4.months;
# 9
在这里你可以试试这个。它基本上检查您的数字是年还是月。脚本只是一个模板,你可以继续它并改进它,从中创建一个函数,或者定义你自己的原型。只需检查代码,希望它有帮助。
var a = '65.00'.split('.');
var b = '47.09'.split('.');
a = a[0] * 12 + Number(a[1]);
b = b[0] * 12 + Number(b[1]);
c = a - b;
c = Math.floor(c / 12) + (c % 12) / 100;