Convert time to a float

I've got a stopwatch app that stores the times in an array. The JS counts milliseconds from when the timer is started, then converts those milliseconds into seconds and minutes, and outputs that as a string.

What I'm trying to do is calculate the averages of these times, so I have to convert the strings into floats. It can convert a string like 10.35 to a float just fine, but it obviously doesn't work with something like 1:24.56, that's what I'm trying to fix. The time will be in one of these formats:

[seconds].[milliseconds]
[minutes]:[seonds].[milliseconds]

Any ideas? I'm really new with Javascript so I'm not sure where to go with this.

EDIT: The repo is here. All of the nonsense happens in the timer.js and main.js files.

Answers:

Answer

Just split it, and add it up:

function toMS(str) {
  if(!str.includes(":"))
     return parseFloat(str);
  const [mins, secms] = str.split(":");
  const [sec, ms] = secms.split(".");
  return ((+mins * 60) + +sec) * 1000 + +ms;
}

(This uses "unary plus operators" to convert the strings into numbers)

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.