I have an array of start/stop times. I basically want to display the time it took for each entry, as well as the total time for all of them. Here is the code I wrote to try to do that:
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);
However, I am losing accuracy. As you can see, the individual times don't add up to the mainTimer
value. It is always off by .01 - .03 no matter what the times are.
Is there a way I can make sure that the times only display two places, but still add up correctly? Any help would be appreciated.
I also have this on a JSFiddle where it's easier to run.
EDIT: The current answer did work for the case I provided above, but it does not work for all cases like this one.