2

I'm currently try to display a grid for the monthly returns of a stock portfolio for multiple years.

Currently the data is being displayed as a decimal to the nearest hundredth, how can I convert the decimal to a percentage to the nearest tenth of a percent?

code:

angular.module('TestCtrl', []).controller('TestController', function($scope, $http, $filter, FUNDS, DATES, FUNDMAP, BENCHMARKS, BENCHMARKMAP) {

  $scope.start = new Date(DATES.minDate);
  $scope.end = new Date(DATES.maxDate)
  $scope.minDate = new Date(DATES.minDate);
  $scope.maxDate = new Date(DATES.maxDate);

  $scope.items = FUNDS;
  $scope.benchmarks = BENCHMARKS

  var cellColor = function(grid, row, col, rowIndex, colIndex) {
    var val = grid.getCellValue(row, col);
    if(val < 0) {
      return 'red';
    }
  }

  $scope.gridOptions = {
    columnDefs: [{ field: 'year', displayName: 'Year' },
                { field: 'January', displayName: 'Jan',
                  cellClass: cellColor},
                { field: 'February', displayName: 'Feb',
                  cellClass: cellColor},
                { field: 'March', displayName: 'Mar' ,
                  cellClass: cellColor},
                { field: 'April', displayName: 'Apr' ,
                  cellClass: cellColor},
                { field: 'May', displayName: 'May',
                  cellClass: cellColor },
                { field: 'June', displayName: 'June',
                  cellClass: cellColor },
                { field: 'July', displayName: 'July',
                  cellClass: cellColor },
                { field: 'August', displayName: 'Aug',
                  cellClass: cellColor },
                { field: 'September', displayName: 'Sept',
                  cellClass: cellColor },
                { field: 'October', displayName: 'Oct',
                  cellClass: cellColor },
                { field: 'November', displayName: 'Nov',
                  cellClass: cellColor },
                { field: 'December', displayName: 'Dec',
                  cellClass: cellColor },
                { field: 'YearlyReturn', diplayNmae: 'Yearly', cellClass: cellColor}]
}

$scope.calculate = function() {
  var months = [ "January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"];
  var shortMonth = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  $scope.chartData = {
    returns: [],
    labels: [],
    series: []
  }
  var fundName = FUNDMAP[$scope.data.fund]
  $scope.config = {
    params:{
      startDate:$filter('date')($scope.start, "yyyy-MM-dd"),
      endDate:$filter('date')($scope.end, "yyyy-MM-dd"),
      cik:$scope.data.fund,
      startingAmount:10000,
      benchmark:$scope.data.benchmark
    }
  }

  $http.get('/api/returns', $scope.config).success(function(data) {

    var labels = []
    var returnsList = [];
    var values = []
    $scope.chartData.series.push(fundName)
    for(var d in data['requested']) {
      for(var i in months)
        if(data['requested'][d].hasOwnProperty(months[i])) {
          labels.push(data['requested'][d]['year'] + " " + shortMonth[i] )
          values.push(data['requested'][d][months[i]])
        }
    }
    $scope.chartData.returns.push(values)

    angular.forEach(data['benchmark'], function(value, key) {
      values = []
      for(var d in value) {
        for(var i in months) {
          if(value[d].hasOwnProperty(months[i])) {
            values.push(value[d][months[i]])
          }
        }
      }
      $scope.chartData.series.push(BENCHMARKMAP[$scope.data.benchmark])
      $scope.chartData.returns.push(values)
    })

    $scope.gridOptions.data = data['requested']

    $scope.chartData.labels = labels

  }).error(function() {
    alert("Error");
  })
};

//weekdays only
$scope.noWeekendsPredicate = function(date) {
    var day = date.getDay();
    return day > 0 && day < 6;
  }

//make sure date is after start date
  $scope.greaterThanStart = function(date) {
    var day = date.getDay();
    if(day === 0 || day === 6) {
        return false;
    }

    if(date.getYear()!=$scope.start.getYear()) return date.getYear() > $scope.start.getYear();
    else if(date.getMonth()!=$scope.start.getMonth()) return date.getMonth()> $scope.start.getMonth();
    else if(date.getDate()!=$scope.start.getDate()) return date.getDate() > $scope.start.getDate();
    return false;
  }

});

HTML code:

<html>
  <div class="jumbotron text-center">
    <h1> Returns </h1>


    <form class="form-inline">
      <label for="singleSelectFund">Portfolio:</label>
      <select name="singleSelectFund" id="singleSelectFund" ng-model="data.fund" required>
        <option value="">---Please select---</option>
        <option ng-repeat="option in items" value="{{option.id}}">{{option.name}}</option>
      </select>

      <label for="singleSelectBenchmark">Benchmark:</label>
      <select name="singleSelectBenchmark" id="singleSelectBenchmark" ng-model="data.benchmark" required>
        <option value="">---Please select---</option>
        <option ng-repeat="option in benchmarks" value="{{option.code}}">{{option.name}}</option>
      </select><br>

         <button type="submit" class="btn btn-primary" ng-click="calculate()">Calculate</button>
    </form>

    <div id="grid1" ui-grid="gridOptions" class="grid"></div>


  </div>
</html>

CSS code:

.grid .ui-grid-row .black {
  color: black;
}

.grid .ui-grid-row .red {
  color: red;
}

Thank you for any help

user3628240
  • 877
  • 1
  • 23
  • 41

1 Answers1

0

You can create a custom filter to convert the number to a percentage like this:

.filter('percentage_filter', function($filter) {
  return function(input) {

    if (undefined === input || null === input) {
      return "";
    }

    var output = (input * 100).toFixed(0).replace(".", ",");

    return output;
  };
});

If the input is undefined or null you could return anything ie. text. The replace in the output is not necessary if you want to convert it to a integer.

Here's a JSFiddle: https://jsfiddle.net/thepio/u4bmwcsq/

thepio
  • 6,193
  • 5
  • 35
  • 54
  • sorry, I'm still a little bit new with angular, I updated the post to copy the entire code, could you tell me where you would put the custom filter? Also, currently if the number is negative then it should be red, will the filter affect this? Thank you – user3628240 Sep 05 '16 at 06:17
  • Currently the filter will not affect the color of the output. Let mee see your updated question and get back to you in a few minutes. – thepio Sep 05 '16 at 06:20
  • You know there's just too many unknown factors and things in your code that it might be impossible for me to help you any further. You could just read somewhere how to include a filter in AngularJS and go on from there. – thepio Sep 05 '16 at 06:41
  • Ok, thank you very much for your help. So I definitely just need to figure out where in the controller to put the filter right? – user3628240 Sep 05 '16 at 06:44
  • No problem, sorry I can't help you further. But this I can say. You do not put the filter in the controller but as in my example it's a separate block of code. I'm not sure how you have structured your code but it could even go in a separate file and then you just include it in your index.html etc. – thepio Sep 05 '16 at 06:49