I have an algorithim where it calculates the total duration remaining. The format of the duration is ’00 Hrs 00 Mins 00 Secs’. How the calculation works is like this for example:
if total duration remaning is 01 Hrs 30 Mins 20 Secs and user enters in duration 00 Hrs 50 Mins 00 Secs and adds the row, then 01 Hrs 30 Mins 20 Secs minus 00 Hrs 50 Mins 00 Secs will make new total duration remaining equal 00 Hrs 40 Mins 20 Secs.
If the total duration goes into negative then format goes like this : – 00 Hrs 00 Mins 00 Secs
I have a couple of problems though:
Problem 1:
Lets say total duration remaining is ’00 Hrs 00 Mins 50 Secs’. Then if I add 00 Hrs 00 Mins 50 Secs twice, the total duration remaining should equal ‘- 00 Hrs 00 Mins 50 Secs’
But instead it is displaying this ‘ – 00 Hrs 01 Mins 0-10 Secs’.
Problem 2:
Lets say total duration remaining is ’00 Hrs 50 Mins 00 Secs’. Then if I add 00 Hrs 50 Mins 00 Secs twice, the total duration remaining should equal ‘- 00 Hrs 50 Mins 00 Secs’
But instead it is displaying this ‘ – 01 Hrs 0-10 Mins 00 Secs.
This is a strange problem. But I beleive this problem is happening because of my algrorithm. So my question is that does anyone know how to fix the algrorithm if the algrorithm is at fault?
Below is the code:
var format = duration.match(/(\d\d)/ig),
hours = parseInt(format[0], 10),
mins = parseInt(format[1], 10),
secs = parseInt(format[2], 10);
function calculateDuration()
{
var totalduration = duration;
var sign = '';
var tmp_hours = 0;
var tmp_mins = 0;
var tmp_secs = 0;
$("#qandatbl td.duration input").each(function (){
tmp_format = $(this).val().match(/(\d\d)/ig),
tmp_hours += parseInt(tmp_format[0], 10),
tmp_mins += parseInt(tmp_format[1], 10),
tmp_secs += parseInt(tmp_format[2], 10);
});
tmp_mins += Math.floor(tmp_secs / 60);
tmp_secs = tmp_secs % 60;
tmp_hours += Math.floor(tmp_mins / 60);
tmp_mins = tmp_mins % 60;
newH = hours - tmp_hours;
newM = mins - tmp_mins;
newS = secs - tmp_secs;
if( newS < 0 ) {
newS += 60;
newM--;
}
if( newM < 0 ) {
newM += 60;
newH--;
}
if(newH < 0) {
newM = Math.abs(newM - 60);
newH = Math.abs(newH + 1);
sign = '- ';
}
checkedH = (newH < 10 ? '0' : '') + newH;
checkedM = (newM < 10 ? '0' : '') + newM;
checkedS = (newS < 10 ? '0' : '') + newS;
new_duration = sign + checkedH + ' Hrs ' + checkedM + ' Mins ' + checkedS + ' Secs';
$("#total-duration").text(new_duration);
}
Thank you
updated answer
Rewrote the algorithm to deal with seconds only
demo at http://jsfiddle.net/gaby/4xjcW/1/
original answer
Use the
Math.absto get the absolute value..The problem is that you are returning
0as a string and adding-10so it becomes0-10