0

Hello I have a function where I am summing datas from JSON obj.

  $scope.sum = function(username){
        //console.log(username);
        let model = $scope.data.filter(function(item) {
          return item.username == username
        });

        let tests = {};
        model.forEach(function(item) {
          if(!tests.hasOwnProperty(item.dept)){
            tests[item.dept] = 0;
          }
          tests[item.dept] += parseFloat(item.task_time) / 60;


        });

        $scope.data.model = tests;
      //  console.log(tests);
        //console.log($scope.data.model);
      }

I am dividing by 60 and it works but result is like 263.08333333333354 I want to have result like 263.08 Is it possible?

Defus
  • 789
  • 2
  • 12
  • 22
  • 1
    Filter the tests before giving them to the model - `tests = tests.filter(function(num) { return num.toFixed(2) });` - that is a better way – mplungjan Mar 14 '17 at 13:40
  • @mplungjan TypeError: tests.filter is not a function – Defus Mar 14 '17 at 13:45
  • 1
    Sorry. I thought it was an array. `var tests = {"a":123.345,"b": 345.678,"c": 987.345}; Object.keys(tests).map(function(objectKey, index) { tests[objectKey]=tests[objectKey].toFixed(2); }); console.log(tests);` – mplungjan Mar 14 '17 at 15:10
  • @mplungjan it works but I have one more question what if I have array of objects? It doesn't work – Defus Mar 14 '17 at 17:59
  • 1
    Then you do filter: `tests = tests.filter(function(obj) { obj.dept=obj.dept.toFixed(2); return obj; });` – mplungjan Mar 14 '17 at 18:03
  • @mplungjan I did like that http://pastebin.com/QEKs6Axc but I am getting error item.dept.toFixed is not a function – Defus Mar 14 '17 at 18:16
  • 1
    .dept of course has to be a number `tests = tests.filter(function(obj) { obj.dept=obj.dept && !isNaN(obj.dept)?obj.dept.toFixed(2):"0.00"; return obj; });` – mplungjan Mar 14 '17 at 18:20
  • @mplungjan it's a little weird but works fine ;) Thank you very much – Defus Mar 14 '17 at 18:30
  • 1
    It's called defensive coding – mplungjan Mar 14 '17 at 18:34
  • @mplungjan Cool I'll learn it. Now I am fighting with conversion from minutes do hrs. I want to do something like time in minutes / 60 and time in minutes % 60 then unite it to get time in hrs and minutes. In my Database I have time in INT like 40,50,60 – Defus Mar 14 '17 at 19:03
  • 1
    Search SO or google. Hundreds of examples "convert minutes to hours and minutes" – mplungjan Mar 14 '17 at 19:10

0 Answers0