0

I'm currently writing the working hour calculation with Time In and Time Out to show working hour with decimal with 1 point. In my case i used .toFixed(1) and any other times are working well but when time in is 09:10 and time out is 17:30 .. It's result show as 8.333333333333334. .toFixed(1) not working in that decimal number. How should i do that.

Here is my code.

var time_in = $(elm).closest('tr').find('.time_in').text();
var time_out = $(elm).closest('tr').find('.time_out').text();
var working_time = (new Date("1970-1-1 " + time_out) - new Date("1970-1-1 " + time_in)) / 1000 / 60 / 60 ;
alert(working_time);
var total_work_hour = working_time.toFixed(1) - 1;    //get fixed decimal number and minus 1 for lunch time.
var w_time = $(elm).closest('tr').find('.work_time');
w_time.text(total_work_hour);
Kawazoe Kazuke
  • 175
  • 6
  • 20
  • 6
    `8.333333333333334.toFixed(1)` results in `8.4`. I do not understand the issue. You are also alerting `working_time` and not `working_time.toFixed(1)` so your test is invalid. – Shawn31313 Nov 08 '17 at 03:41
  • please do a typeof and check if 8.3333333.... is a number.It is working fine in my case.Also note if there is any error in console – brk Nov 08 '17 at 03:41
  • You should not rely on the `Date` constructor being able to reliably parse those date/time strings. – Phil Nov 08 '17 at 03:43
  • @Shawn31313 - No, it is 8.3. Not 8.4. – Jeff McMahan Nov 08 '17 at 03:53
  • The result is 8.3, what are you expecting? – Daniel Tran Nov 08 '17 at 03:55
  • I think OP is getting 7.3000000000001 when subtracting 1 from 8.3, and is mistakenly thinking that's because `.toFixed(1)` is not working. In fact, it's because the math is floating point. – Jeff McMahan Nov 08 '17 at 03:57
  • Why are you rounding _before_ your calculations are done? Round at the end. – JLRishe Nov 08 '17 at 03:59

1 Answers1

1

When you subtract 1 from the result of 8.333333333333334.toFixed(1) (which javascript allows you to do even though Number#toFixed returns a string), the result is not 7.3 because the machine is using binary floating point arithmetic. For example:

0.1 + 0.2 // -> 0.30000000000000004

To get around this, do all your arithmetic and then call .toFixed(1):

var total_work_hour = (working_time - 1).toFixed(1);
Jeff McMahan
  • 1,324
  • 12
  • 15