我正在为我正在创建的一个小型Web应用程序创建我自己的自定义TimeObject
类。JavaScript函数转换毫秒产生奇怪的结果
在这里,我定义一个函数来截取的有效范围,毫秒整数,以实例化TimeObject
如下:
TimeObject.prototype.millisecondsToTime = function(mm) {
function valid() {
if(parseInt(mm,10) >= 0 && parseInt(mm,10) <= 359999999) return true;
}
if(valid()) {
var h = Math.floor(mm/3600000);
var m = Math.floor(((mm/3600000)-h)*60);
var s = Math.floor(((((mm/3600000)-h)*60)-m)*60);
var mmFinal = Math.floor(((((((mm/3600000)-h)*60)-m)*60)-s)*1000);
this.hours = h,
this.minutes = m;
this.seconds = s;
this.milliseconds = mmFinal;
} else {
this.hours = 0,
this.minutes = 0;
this.seconds = 0;
this.milliseconds = 0;
}
}
似乎除了那些值很好地工作2^x的:
// 2^0 = 1 -> returns 0, should return 1
// 2^1 = 2 -> returns 1, should return 2
// 2^2 = 4 -> returns 3, should return 4
// 2^3 = 8 -> returns 7, should return 8
// And so on...
值,如1001
,1003
,但不1002
和1004
为0
和2
资源回报milliseconds
pectively。他们应该返回1
和3
作为milliseconds
值,但不要。
我知道这是一个逻辑错误,但这里发生了什么,我该如何纠正我的代码?
尝试使用整数代数而不是分割和乘数次。请记住,浮点运算会丢失小数精度 – 2014-09-23 16:34:20