【发布时间】:2016-08-14 05:54:06
【问题描述】:
我有一组开始/停止时间。我基本上想显示每个条目所花费的时间,以及所有条目的总时间。这是我写的代码:
function timeFormatter (milliseconds) {
const padZero = (time) => `0${time}`.slice(-2);
const minutes = padZero(milliseconds / 60000 | 0);
const seconds = padZero((milliseconds / 1000 | 0) % 60);
const centiseconds = padZero((milliseconds / 10 | 0) % 100);
return `${minutes} : ${seconds} . ${centiseconds}`;
}
// Example stopwatch times
const timeIntervals = [
{ startTime: 1470679294008, stopTime: 1470679300609 },
{ startTime: 1470679306278, stopTime: 1470679314647 },
{ startTime: 1470679319718, stopTime: 1470679326693 },
{ startTime: 1470679331229, stopTime: 1470679336420 }
];
// Calculate time it took for each entry
const times = timeIntervals.map(time => time.stopTime - time.startTime);
// Run the timeFormatter on each individual time
const individualTimes = times.map(timeFormatter);
// Run the timeFormatter on the sum of all the times
const mainTimer = timeFormatter(times.reduce((a, b) => a + b));
/**
* [
* '00 : 06 . 60',
* '00 : 08 . 36',
* '00 : 06 . 97',
* '00 : 05 . 19'
* ]
*/
console.log(individualTimes);
/**
* 00 : 27 . 13
*/
console.log(mainTimer);
但是,我正在失去准确性。如您所见,各个时间加起来不等于mainTimer 值。无论什么时候,它总是关闭 0.01 - 0.03。
有没有一种方法可以确保时间只显示两个地方,但仍然正确相加?任何帮助将不胜感激。
我在 JSFiddle 上也有这个,它更容易运行。
编辑:当前答案确实适用于我上面提供的案例,但不适用于所有案例,例如this one。
【问题讨论】:
-
如果你这样做
const centiseconds = padZero((Math.round(milliseconds / 10) | 0) % 100);你不会失去准确性。
标签: javascript ecmascript-6 rounding precision