RoundUp - AngularJS

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-27 04:43:16

问题


I am using the following code to try and roundup in Angular, which on the whole works, however numbers less than 0.5 are rounded to 0. I would like to round up every number to the next whole number. E.g 0.02 should be rounded to 1

{{((data.Virtual.SumCores/data.Physical.SumCores) | number:0)*1}}


回答1:


Use this

Math.ceil(4.4); //Returns 5
Math.ceil(0.002); //Returns 1

The filter

 .filter('roundup', function () {
        return function (value) {
            return Math.ceil(value);
        };
    })

The HTML

{{ yourdata | roundup }}

reference

JS Math




回答2:


If you add 0.999 first, it should round up instead of down.




回答3:


You can create a filter for this:

.filter('roundup', function() {
  return function(input) {
    return Math.ceil(input);
  };
});

And use it like this:

{{ data.Virtual.SumCores/data.Physical.SumCores | roundup }}



回答4:


Since all of the answers are based on Math.ceil() function, you can simply add

$scope.Math=window.Math;

into your controller and use it like this:

{{ Math.ceil(data.Virtual.SumCores/data.Physical.SumCores) }}

This way you get the access to all Math functions.




回答5:


you should create a new filter to do that:

angular.module('myApp', [])
.filter('ceil', function(){
  return function(input) {
    return Math.ceil(+input);
  };
})
.controller('myCtrl', ['$scope', function($scope){
  $scope.numbers = [0.2,1.5,1.3,5.5,3,10,0.5];
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

  <div ng-repeat="n in numbers">
    {{n | ceil}}
  </div>

</div>


来源:https://stackoverflow.com/questions/32649376/roundup-angularjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!