1

I've used a time to hours, minutes, seconds function from here: Javascript seconds to minutes and seconds

Which works fine, except for when the time has milliseconds on the end.

This is the current (semi-modified) JS block:

var time = 122, // example time (2 minutes, 2 seconds)
  mins = ~~(time / 60),
  secs = time % 60;

 var hrs = ~~(time / 3600),
  mins = ~~((time % 3600) / 60),
  secs = time % 60;

 var ft = "";

 if (hrs > 0) {
     ft += "" + hrs + ":" + (mins < 10 ? "0" : "");
 }
 ft += "" + mins + ":" + (secs < 10 ? "0" : "");
 ft += "" + secs;
console.log(ft);

The above JavaScript block works completely fine. However, if I were to change time equal to 122.33, it will print something like:

2:02.3299999999999983

How would I fix this?

Thanks.

EDIT:

Forgot to mention that this is not for converting time zone. It is for converting seconds to minutes & seconds (and hours if the audio spans for that long).

Community
  • 1
  • 1
GROVER.
  • 4,071
  • 2
  • 19
  • 66

4 Answers4

1

Apply with Math.round() function it will rounded the values.

Refer the link

Math

var time = 122.33, // example time (2 minutes, 2 seconds)
  mins = ~~(time / 60),
  secs = time % 60;

 var hrs = ~~(time / 3600),
  mins = ~~((time % 3600) / 60),
  secs = time % 60;

 var ft = "";

 if (hrs > 0) {
     ft += "" + hrs + ":" + (mins < 10 ? "0" : "");
 }
 ft += "" + mins + ":" + (secs < 10 ? "0" : "");
 ft += "" +Math.round( secs);
console.log(ft);
prasanth
  • 22,145
  • 4
  • 29
  • 53
1

use Math.trunc(time); for example Math.trunc(122.33); // 122

Rafiqul Islam
  • 1,636
  • 1
  • 12
  • 25
0

Unless there's a very compelling reason, you shouldn't be writing time conversions/formatting yourself. See this youtube for why.

Checkout the momentjs library. If you want to do a bit more work and avoid a dependency, use the Date built-in library.

e.g. with MomentJS

> var moment = require('moment');
> var x_seconds = 122.33;
> moment(moment.duration(x_seconds, 'second').asMilliseconds()).format("mm:ss.SSS");
'02:02.330'
rmharrison
  • 4,730
  • 2
  • 20
  • 35
  • .. this isn't for a time zone. it's for converting seconds in a song. – GROVER. Oct 31 '16 at 07:01
  • I know, was making a general point. Both libs will do conversions, as well as duration/diffs. Trying to roll this stuff yourself is buggy and will cause you pain down the road. Just use a lib and be done with it. – rmharrison Oct 31 '16 at 07:03
  • I'm not using a library for something this simple. it is incredibly pointless. especially when it's able to be done in one JavaScript block. – GROVER. Oct 31 '16 at 07:04
0

There are many ways of solving your problem. But an easy way to do this is to try .toFixed(n)

For eg: var x = 10/3 ; x.toFixed(3) would give you precision to 3 decimal places.

GROVER.
  • 4,071
  • 2
  • 19
  • 66