badjuju badjuju - 1 month ago 6
Javascript Question

minutes and seconds function outputting unwanted numbers to end if time contains milliseconds

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).

Answer

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);

Comments