我正在爲我正在創建的一個小型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